上一篇文章是支付宝的扫码支付,现在国内差不多就这几种支付,支付宝、微信、银行卡。
微信扫码支付:
第一步:
设置需要的参数:
1.App ID:公众账号ID
2.MCHID:商户号
3.KEY:商户密钥
4.keyPath:商户证书路径
5.notifyUrl:异步通知地址
参数获取方法
public String getAppID() {
return "wx88b8861bd*********";
}
public String getMchID() {
return "1607521***";
}
public String getKey() {
return "37238wy2763dfg4322FSADg******";
}
public String getCreateIp(){
return "106.14.*.*";
}
public String getNotifyUrl(){
return "https://106.14.*.*/pay/callback/wxpay";
}
public InputStream getCertStream() {
ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
return certBis;
}
第二步:
导入需要用到的jar包
<!-- 微信支付 -->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
<!-- 解析xml-->
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.0</version>
</dependency>
第三步:
微信支付接口:
//微信支付
@RequestMapping("/wxpay")
@ResponseBody
public Object WxPayMethord() throws Exception {
//判断用户是否登录,如果登录则返回用户中心,否则返回登录界面
UserSession userSession = UserSession.getCurrentUserSession();
String id = userSession.getUserId();
if (StringUtil.isEmpty(id)) {
return R.fail("登录超时,请重新登录后再试!");
}
Map map = new HashMap();
//添加或更新订单信息
String orderNo = "";
OperatePersonnel operatePersonnel = operatePersonnelService.get(id);
if (null != operatePersonnel) {
orderNo = dealService.saveOrUpdate(operatePersonnel, AlipayConfig.amount);
}
WXConfig config = new WXConfig();
WXPay wxpay = new WXPay(config);
//沙箱环境,用于测试使用
// WXPay wxpay = new WXPay(config, WXPayConstants.SignType.MD5, true);
Map<String, String> data = new HashMap<String, String>();
data.put("body", AlipayConfig.name);//商品简单描述
data.put("out_trade_no", orderNo);
data.put("device_info", "");
data.put("fee_type", "CNY");//币种:默认人民币
int money=new Double(AlipayConfig.amount).intValue();
data.put("total_fee", String.valueOf(money));//订单金额(分)即1元等于100分
data.put("spbill_create_ip", config.getCreateIp());//APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
data.put("notify_url", config.getNotifyUrl());
data.put("trade_type", "NATIVE"); // 此处指定为扫码支付
// data.put("product_id", deals.getProduct_id());//商品编码 由卫计委在微信端设置编码值
Map<String, String> resp = null;
try {
if (StringUtil.isNotEmpty(orderNo)) {
resp = wxpay.unifiedOrder(data);
log.info(String.valueOf(resp));
map.put("resp", resp);
map.put("result", "创建微信支付订单成功!");
return R.success(map);
}
return R.fail("订单创建失败!");
} catch (Exception e) {
e.printStackTrace();
return R.fail("创建微信支付订单失败!");
}
}
返回信息中取出地址,生成二维码,前端需要画页面。
第四步:
写回调地址
@RequestMapping(value = "/wxpay")
@ResponseBody
public void weixinNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
//读取参数
System.out.println("进入微信回调");
InputStream inputStream;
StringBuffer sb = new StringBuffer();
inputStream = request.getInputStream();
String s;
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((s = in.readLine()) != null) {
sb.append(s);
}
in.close();
inputStream.close();
//解析xml成map
Map<String, String> m = new HashMap<String, String>();
m = XMLUtil.doXMLParse(sb.toString());
//过滤空 设置 TreeMap
SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String parameter = (String) it.next();
String parameterValue = m.get(parameter);
String v = "";
if (null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
System.out.println(packageParams);
// 账号信息
WXConfig config = new WXConfig();
String key = config.getKey(); // key
//判断签名是否正确
if (WxpayUtil.isTenpaySign("UTF-8", packageParams, key)) {
System.out.println("签名正确!");
//------------------------------
//处理业务开始
//------------------------------
String resXml = "";
if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
// 这里是支付成功
//执行自己的业务逻辑
String out_trade_no = (String) packageParams.get("out_trade_no");
//获取用户订单信息
Deal deal = dealService.findByOrderNo(out_trade_no);
if (null != deal) {
deal.setUpdateTime(new Date());
deal.setIsPayed(Deal.PAYED_SUCCESS);
deal.setPayChannel(Deal.PAY_CHANNEL_PC);
deal.setPayedTime(new Date());
deal.setPayType(Deal.PAY_TYPE_WX);
boolean a = dealService.updateSelective(deal);
if (!a) {
System.out.println(out_trade_no + ":订单更新失败!");
log.error(out_trade_no + ":订单更新失败!");
} else {
System.out.println(out_trade_no + "订单更新成功!");
System.out.println(out_trade_no + "订单支付成功!");
log.info(out_trade_no + "订单支付成功!");
}
}
//通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
} else {
log.info("支付失败,错误信息:" + packageParams.get("err_code"));
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
}
//------------------------------
//处理业务完毕
//------------------------------
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
} else {
System.out.println("通知签名验证失败");
log.info("通知签名验证失败");
}
}
这里需要准备一些util
1.MD5Util
package com.paladin.common.utils;
import java.security.MessageDigest;
/**
* Created with IntelliJ IDEA.
* Description:
* User: luckywcw
* Date: 2021-04-08
* Time: 14:10
*/
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
2.WxpayUtil
package com.paladin.common.utils;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
public class WxpayUtil {
/**
* 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
* @return boolean
*/
public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
//算出摘要
String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
//System.out.println(tenpaySign + " " + mysign);
return tenpaySign.equals(mysign);
}
/**
* @author
* @date 2016-4-22
* @Description:sign签名
* @param characterEncoding
* 编码格式
* @param packageParams
* 请求参数
* @return
*/
public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
* @author
* @date 2016-4-22
* @Description:将请求参数转换为xml格式的string
* @param parameters
* 请求参数
* @return
*/
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
}
3.XMLUtil
package com.paladin.common.utils;
/**
* Created with IntelliJ IDEA.
* Description:
* User: luckywcw
* Date: 2021-04-08
* Time: 13:57
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class XMLUtil {
/**
* 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if(children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = XMLUtil.getChildrenText(children);
}
m.put(k, v);
}
//关闭流
in.close();
return m;
}
/**
* 获取子结点的xml
* @param children
* @return String
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if(!children.isEmpty()) {
Iterator it = children.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if(!list.isEmpty()) {
sb.append(XMLUtil.getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
}
最后,遇到的坑。
1.首先微信的appid,公众号的appid必须与商户的mchid关联起来
2.回调的url外网能够访问
3.设置的金额单位是分