微信支付之JSAPI开发-java
话不多说直接上代码,前面准备商户号 公众号 关联账号之类的就不说了,直接找产品要 喊他们准备。
开发之前一定要找产品说清楚你需要微信支付的那些账号 (微信支付的商户id, 微信支付的商户密钥,微信正式账号的 appid secret )。
配置yml
notify_url:就是微信支付成功后回调你后端的连接,需要用线上的域名,或者弄一个内网穿透调试(我用的是natapp,https://natapp.cn/ 下载注册地址)
applet:
#微信商户号
#微信支付的商户id
mch_id:
#微信支付的商户密钥
key:
#微信正式账号
appid:
secret:
grantType: authorization_cod
#支付成功后的服务器回调url,这里填Controller里的回调函数地址
notify_url:
配置 WechatConfig
package com.showtime.serviceschool.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* @Author cjb
*
* @Date 2020/1/8
*
* @Description //TODO 微信支付配置类
*/
@Component
@Data
public class WechatConfig implements Serializable {
//小程序appid 开发者自己拥有的
@Value("${applet.appid}")
public String appid;
//微信支付的商户id 开发者去问自己id的前端同事或者领导。
@Value("${applet.mch_id}")
public String mch_id;
//微信支付的商户密钥 开发者问领导,去微信商户平台去申请(要下插件等等)
@Value("${applet.key}")
public String key;
//支付成功后的服务器回调url,这里填Controller里的回调函数地址
@Value("${applet.notify_url}")
public String notify_url;
//签名方式,固定值
public static final String SIGNTYPE = "MD5";
//交易类型,微信H5支付的固定值为MWEB,JSPAI的支付的固定值为JSAPI
public static final String TRADETYPE = "JSAPI";
//微信统一下单接口地址
public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//微信查看订单地址
public static final String order_query_url = "https://api.mch.weixin.qq.com/pay/orderquery";
//关闭订单地址
public static final String close_order_url = "https://api.mch.weixin.qq.com/pay/closeorder";
//微信外H5支付的域名,如果是微信内支付无视这段
public static final String company_website = "";
}
WxpayUtil 工具
package com.showtime.serviceschool.utils;
import com.showtime.serviceschool.config.WechatConfig;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.net.*;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;
/**
* @Author cjb
* @Date 2019/4/30 9:03
* @Description //TODO 微信支付工具
*/
@Component
public class WxpayUtil {
private static final String STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@Autowired
private WechatConfig wechatConfig;
/**
* <p>方法说明: TODO 获取微信回调地址
* <p>创建时间: 2019年4月30日 下午1:21:05
* <p>创 建 人: cjb
**/
public String getNotifyUrl(HttpServletRequest request) {
StringBuffer requestURL = request.getRequestURL();
return requestURL.substring(0, requestURL.indexOf("/front/")) + wechatConfig.getNotify_url();
}
/**
* <p>方法说明: TODO 统一下单 参数处理
* <p>参数说明: String orderNo 订单号
* <p>参数说明: String totalAmount 订单总金额
* <p>参数说明: String notifyUrl 回调通知地址
* <p>参数说明: String body 订单描述
* <p>返回说明:
* <p>创建时间: 2019年4月30日 上午9:56:23
* <p>创 建 人: cjb
**/
public String getUnifiedOrder(String orderNo, String totalAmount, String notifyUrl, String body, String openId) {
SortedMap<String, Object> paramMap = new TreeMap<>();
//应用ID
paramMap.put("appid", wechatConfig.getAppid());
//商户号
paramMap.put("mch_id", wechatConfig.getMch_id());
//
paramMap.put("device_info", "WEB");
//随机字符串
paramMap.put("nonce_str", getNonceStr(null));
//商品描述
paramMap.put("body", body);
//商户订单号
paramMap.put("out_trade_no", orderNo);
//支付总金额
paramMap.put("total_fee", Integer.parseInt(getTotalFee(totalAmount)));
//当前本机IP
paramMap.put("spbill_create_ip", getLocalhostIP());
//回调通知地址
paramMap.put("notify_url", notifyUrl);
paramMap.put("openid", openId);
//支付类型
paramMap.put("trade_type", wechatConfig.TRADETYPE);
//场景信息(外部H5使用)
// paramMap.put("scene_info", "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":"+wechatConfig.company_website+",\"wap_name\": \"可视化校园支付\"}}");
//数据签名
paramMap.put("sign", rsaSign(paramMap));
//请求参数
return getRequestXML(paramMap);
}
/**
* <p>方法说明: TODO 返回APP 参数处理
* <p>参数说明: String prepayId 预支付交易会话ID
* <p>返回说明:
* <p>创建时间: 2019年4月30日 上午10:00:30
* <p>创 建 人: cjb
**/
public String getReturnParam(Map<String, Object> receiveMap) {
String timestamp = (System.currentTimeMillis() + "").substring(0, 10);
SortedMap<String, Object> returnMap = new TreeMap<>();
//小程序ID
returnMap.put("appId", wechatConfig.getAppid());
//时间戳
returnMap.put("timeStamp", timestamp);
//prepayId
returnMap.put("package", "prepay_id=" + receiveMap.get("prepay_id"));
//signType
returnMap.put("signType", wechatConfig.SIGNTYPE);
//随机字符串
returnMap.put("nonceStr", receiveMap.get("nonce_str"));
//签名
returnMap.put("paySign", rsaSign(returnMap));
//请求参数
return getRequestXML(returnMap);
}
/**
* <p>方法说明: TODO 关闭/查看 订单 参数处理
* <p>参数说明: String orderNo 商户订单号
* <p>创建时间: 2019年4月30日 下午2:55:53
* <p>创 建 人: cjb
**/
public String closeORqueryOrderParam(String orderNo) {
SortedMap<String, Object> returnMap = new TreeMap<>();
returnMap.put("appid", wechatConfig.getAppid()); //小程序ID
returnMap.put("mch_id", wechatConfig.getMch_id()); //商户号
returnMap.put("out_trade_no", orderNo); //商户订单号
returnMap.put("nonce_str", getNonceStr(null)); //随机字符串
returnMap.put("sign", rsaSign(returnMap)); //签名
return getRequestXML(returnMap); //请求参数
}
/**
* <p>方法说明: TODO 验证签名
* <p>参数说明: Map<String,String> paramMap
* <p>返回说明: boolean
* <p>创建时间: 2019年4月30日 上午11:18:47
* <p>创 建 人: cjb
**/
public boolean rsaCheck(Map<String, Object> paramMap) {
System.out.println("↓↓↓↓↓↓↓↓↓↓微信支付签名验证处理↓↓↓↓↓↓↓↓↓↓");
SortedMap<String, Object> paramSorMap = new TreeMap<>();
paramSorMap.putAll(paramMap);
boolean rsaCheck = paramMap.get("sign").equals(rsaSign(paramSorMap));
System.out.println("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
return rsaCheck;
}
/**
* <p>方法说明: TODO sign签名
* <p>参数说明: SortedMap<String,String> paramMap
* <p>返回说明: String
* <p>创建时间: 2019年4月30日 下午3:45:02
* <p>创 建 人: cjb
**/
private String rsaSign(SortedMap<String, Object> paramMap) {
StringBuffer paramStr = new StringBuffer();
Set<Entry<String, Object>> paramSet = paramMap.entrySet();
Iterator<Entry<String, Object>> it = paramSet.iterator();
while (it.hasNext()) {
Entry<String, Object> entry = it.next();
String k = entry.getKey();
String v = String.valueOf(entry.getValue());
if (!StringUtils.isEmpty(v) && !"sign".equals(k) && !"key".equals(k)) {
paramStr.append(k + "=" + v + "&");
}
}
//注:key为商户平台设置的密钥key
paramStr.append("key=" + wechatConfig.getKey());
//注:MD5签名方式
String sign = MD5Util.md5Encode(paramStr.toString()).toUpperCase();
System.out.println("微信签名参数==" + paramStr.toString());
System.out.println("微信签 名 值==" + sign);
return sign;
}
/**
* <p>方法说明: TODO 生成随机字符串
* <p>参数说明: Integer length 默认16
* <p>返回说明: 长度为 length 的字符串
* <p>创建时间: 2019年4月30日 下午2:57:57
* <p>创 建 人: cjb
**/
private String getNonceStr(Integer length) {
length = 32;
StringBuffer nonceStr = new StringBuffer();
for (int i = 0; i < length; i++) {
Random rd = new Random();
nonceStr.append(STR.charAt(rd.nextInt(STR.length() - 1)));
}
return nonceStr.toString();
}
/**
* <p>方法说明: TODO 获取本机IP
* <p>返回说明: 通过 获取系统所有的networkInterface网络接口 然后遍历 每个网络下的InterfaceAddress组,
* 获得符合 "InetAddress instanceof Inet4Address" 条件的一个IpV4地址
* <p>创建时间: 2019年4月30日 下午2:02:20
* <p>创 建 人: cjb
**/
private String getLocalhostIP() {
String ip = null;
Enumeration<?> allNetInterfaces;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
List<InterfaceAddress> interfaceAddress = netInterface.getInterfaceAddresses();
for (InterfaceAddress add : interfaceAddress) {
InetAddress inetAddress = add.getAddress();
if (inetAddress != null && inetAddress instanceof Inet4Address) {
ip = inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("获取IP异常");
}
return ip;
}
/**
* <p>方法说明: TODO 将请求参数转换为XML格式的String
* <p>参数说明: SortedMap<String,String> paramMap
* <p>返回说明: String
* <p>创建时间: 2019年4月30日 下午4:16:21
* <p>创 建 人: cjb
**/
private String getRequestXML(SortedMap<String, Object> paramMap) {
StringBuffer requestXML = new StringBuffer();
requestXML.append("<xml>");
Set<Entry<String, Object>> paramSet = paramMap.entrySet();
Iterator<Entry<String, Object>> it = paramSet.iterator();
while (it.hasNext()) {
Entry<String, Object> entry = it.next();
String k = entry.getKey();
// String v = String.valueOf(entry.getValue());
requestXML.append("<" + k + ">" + entry.getValue() + "</" + k + ">");
}
requestXML.append("</xml>");
System.out.println("微信请求参数==" + requestXML);
return requestXML.toString();
}
/**
* <p>方法说明: TODO 获取整数格式支付总金额
* <p>参数说明: String totalAmount 保留两位小数的金额
* <p>返回说明: String getTotalFee 整数的金额
* <p>创建时间: 2019年4月30日下午5:39:03
* <p>创 建 人: cjb
**/
private String getTotalFee(String totalAmount) {
DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
return decimalFormat.format(Double.valueOf(totalAmount) * 100);
}
/**
* <p>方法说明: TODO 订单查看处理
* <p>创建时间: 2019年4月30日 下午3:34:16
* <p>创 建 人: cjb
**/
public Map<String, Object> orderQuery(String orderNo) throws Exception {
System.out.println("↓↓↓↓↓↓↓↓↓↓微信支付订单查看处理↓↓↓↓↓↓↓↓↓↓");
String receiveParam = HttpUtil.doPostToStr(WechatConfig.order_query_url, closeORqueryOrderParam(orderNo));
return XMLUtil.doXMLParse(receiveParam);
}
/**
* <p>方法说明: TODO 订单关闭处理
* <p>创建时间: 2019年4月30日 下午3:34:16
* <p>创 建 人: cjb
**/
public Map<String, Object> colseOrder(String orderNo) throws Exception {
System.out.println("↓↓↓↓↓↓↓↓↓↓微信支付订单关闭处理↓↓↓↓↓↓↓↓↓↓");
String receiveParam = HttpUtil.doPostToStr(WechatConfig.close_order_url, closeORqueryOrderParam(orderNo));
return XMLUtil.doXMLParse(receiveParam);
}
}
WxpayController
package com.showtime.serviceschool.controller;
import com.showtime.common.model.dto.ResponseJsonCode;
import com.showtime.serviceschool.model.dto.PayDto;
import com.showtime.serviceschool.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @Author cjb
* @Date 2020/1/8 0008
* @Description //TODO 微信支付处理
*/
@Api(description = "微信支付接口")
@RestController
@RequestMapping("/wx/pay")
public class WxpayController {
@Autowired
private WxPayService wxPayService;
/**
* 支付回调处理
*
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping(value = "/wxPayNotify")
public String getPayNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
//支付判断及处理
return wxPayService.getPayNotify(request, response);
}
/**
* 获取数据流数据
*
* @param request
* @return
* @throws IOException
*/
private static String receiveParam(HttpServletRequest request) throws IOException {
StringBuffer receiveParam = new StringBuffer();
InputStream inputStream = request.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader in = new BufferedReader(inputStreamReader);
while (in.readLine() != null) {
receiveParam.append(in.readLine());
}
in.close();
inputStream.close();
System.out.println("微信支付回调参数==" + receiveParam);
return receiveParam.toString();
}
/**
* 微信支付统一下单接口
*
* @param request
* @param pay 前端传入的参数
* @return
*/
@ApiOperation(value = "微信创建订单", notes = "微信创建订单")
@RequestMapping(value = "/front/wxPay", method = RequestMethod.POST)
public ResponseJsonCode wxPay(PayDto pay, HttpServletRequest request) {
return wxPayService.wxPay(pay, request);
}
}
WxPayService
package com.showtime.serviceschool.service;
import com.showtime.common.model.dto.ResponseJsonCode;
import com.showtime.serviceschool.model.dto.PayDto;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Author cjb
* @Date 2020/1/8 0008
* @Description //TODO 微信支付 service
*/
public interface WxPayService {
/**
* 支付回调处理
*
* @param request
* @param response
* @description : //TODO 支付回调处理
* @author : cjb
*/
String getPayNotify(HttpServletRequest request, HttpServletResponse response);
/**
* 微信支付统一下单接口
*
* @param request
* @return
*/
ResponseJsonCode wxPay(PayDto pay, HttpServletRequest request);
}
WxPayServiceImpl 微信支付service 实现类
package com.showtime.serviceschool.service.impl;
import com.showtime.common.exception.MyException;
import com.showtime.common.model.ResultEnum;
import com.showtime.common.model.dto.ResponseJsonCode;
import com.showtime.common.utils.StringUtils;
import com.showtime.serviceschool.config.WechatConfig;
import com.showtime.serviceschool.mapper.slaveSource.StActivationCodeMapper;
import com.showtime.serviceschool.mapper.slaveSource.StActivationOrderMapper;
import com.showtime.serviceschool.model.StActivationCode;
import com.showtime.serviceschool.model.StActivationOrder;
import com.showtime.serviceschool.model.dto.PayDto;
import com.showtime.serviceschool.service.WxPayService;
import com.showtime.serviceschool.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
/**
* @Author cjb
* @Date 2019/5/5 9:32
* @Description //TODO 微信支付service 实现类
*/
@Transactional(rollbackFor = Exception.class)
@Slf4j
@Service
public class WxPayServiceImpl implements WxPayService {
/**
* 微信支付工具
*/
@Autowired
private WxpayUtil wxpayUtil;
/**
* 微信支付配置类
*/
@Autowired
private WechatConfig wechatConfig;
/**
* 3D校园激活码表 Mapper
*/
@Autowired
private StActivationCodeMapper codeMapper;
/**
* 3D校园订单表 Mapper
*/
@Autowired
private StActivationOrderMapper orderMapper;
/**
* 支付回调处理
*
* @param request
* @param response
* @description : //TODO 支付回调处理
* @author : cjb
*/
@Override
public String getPayNotify(HttpServletRequest request, HttpServletResponse response) {
System.out.println("↓↓↓↓↓↓↓↓↓↓微信支付回调业务处理↓↓↓↓↓↓↓↓↓↓");
try {
InputStream inStream = request.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
String result = new String(outSteam.toByteArray(), "utf-8");
System.out.println("微信支付通知结果:" + result);
Map<String, Object> map = null;
try {
/**
* 解析微信通知返回的信息
*/
map = XMLUtil.doXMLParse(result);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("=========:" + result);
// 若支付成功,则告知微信服务器收到通知
if (map.get("return_code").equals("SUCCESS")) {
//签名验证
if (!wxpayUtil.rsaCheck(map)) {
System.out.println("微信支付回调签名验证失败");
throw new MyException(ResultEnum.ST_PAY_ALI_SIGN_FAIL);
}
//-------------------------------↓↓↓↓↓↓↓↓↓↓往数据库中插入订单↓↓↓↓↓↓↓↓↓↓----------------------------------------
try {
//根据订单编号查询数据 nonce_str
String nonceStr = (String) map.get("out_trade_no");
StActivationOrder stActivationOrder = orderMapper.selectOneBySaoReference(nonceStr);
//订单编号
stActivationOrder.setTranOrderNum(String.valueOf(map.get("transaction_id")));
//价格
String totalFee = (String) map.get("total_fee");
//支付完成时间.
String tiemEnd = (String) map.get("time_end");
stActivationOrder.setSaoPayTime(DateUtils.convertDateLocalDateTime(DateUtils.getDate(tiemEnd)));
stActivationOrder.setPayMoney(new BigDecimal(totalFee));
//订单状态(1-未支付,2-已支付)
stActivationOrder.setSaoStatu(2);
//支付完成时间.
String uOpenId = (String) map.get("openid");
stActivationOrder.setUOpenId(uOpenId);
//商户用户账号
int i = orderMapper.updateBySaoReference(stActivationOrder, nonceStr);
if (i == 0) {
throw new MyException(ResultEnum.ST_PAY_FEIGN_INTEGRAL_INSERT_FAIL);
}
} catch (MyException e) {
e.printStackTrace();
}
//-------------------------------↑↑↑↑↑↑↑↑↑↑往数据库中插入订单↑↑↑↑↑↑↑↑↑↑----------------------------------------
System.out.println("---------------------------------------------------------------------------------------------------------------------");
System.out.println("--------------------------------------------微信回调成功!!!!!!-------------------------------------------------");
System.out.println("---------------------------------------------------------------------------------------------------------------------");
return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
}
return "";
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 微信支付统一下单接口
*
* @param request
* @return
*/
@Override
public ResponseJsonCode wxPay(PayDto pay, HttpServletRequest request) {
//判断传入的参数
JudgeNumberUtil.isPositiveNumericIntegration(pay.getType());
JudgeNumberUtil.isStringNull(pay.getUOpenId());
//查询数据库是否存在激活码
StActivationCode code = codeMapper.selectOneActivationCode(pay.getType());
if (code == null) {
return ResponseJsonCode.cusResponseJsonCode(4001, "销量太好激活码已经售完啦~");
}
System.out.println("微信的appId:" + wechatConfig.getAppid());
//随机生成订单号
String orderNo = System.currentTimeMillis() + "" + pay.getType() + "" + (int) ((Math.random() * 9 + 1) * 1000) + "";
//对一笔订单的具体描述
StringBuffer body = new StringBuffer();
body.append("可视化高校");
if (pay.getType() == 1) {
body.append("1");
} else if (pay.getType() == 2) {
body.append("6");
}
body.append("个月体验");
//-------------------------------↓↓↓↓↓↓↓↓↓↓往数据库中插入订单↓↓↓↓↓↓↓↓↓↓----------------------------------------
try {
//插入未支付订单
StActivationOrder order = new StActivationOrder();
//随机生成的订单编号(随机字符串)
order.setSaoReference(orderNo);
//购买类型
order.setSacType(pay.getType());
//订单金额
order.setSaoMoney(getSchoolPrice(pay.getType()));
//订单状态(1-未支付,2-已支付)
order.setSaoStatu(1);
//购买者唯一标识
order.setUOpenId(pay.getUOpenId());
int i = orderMapper.insert(order);
if (i == 0) {
throw new MyException(ResultEnum.ST_PAY_FEIGN_INTEGRAL_INSERT_FAIL);
}
} catch (MyException e) {
e.printStackTrace();
}
//-------------------------------↑↑↑↑↑↑↑↑↑↑往数据库中插入订单↑↑↑↑↑↑↑↑↑↑----------------------------------------
log.info("-----------------------------------------------------------------------------------------------");
log.info("------------------------------------插入订单成功!!!!!!!---------------------------------");
log.info("-----------------------------------------------------------------------------------------------");
//回调地址
Map<String, Object> payment = payment(wechatConfig.getNotify_url(), orderNo, getSchoolPrice(pay.getType()).toString(), body.toString(), pay.getUOpenId());
if (payment == null) {
return ResponseJsonCode.errorRequestJsonCode("500", "不好意思,系统开小差了");
}
try {
return ResponseJsonCode.successRequestMsg("请求成功", XMLUtil.doXMLParse(payment.get("data") + ""));
} catch (JDOMException e) {
e.printStackTrace();
return ResponseJsonCode.errorRequestJsonCode("500", "不好意思,系统开小差了");
} catch (Exception e) {
e.printStackTrace();
return ResponseJsonCode.errorRequestJsonCode("500", "不好意思,系统开小差了");
}
}
/**
* <p>方法说明: TODO 统一下单支付处理
* <p>参数说明: String notifyUrl 回调地址
* <p>参数说明: String orderNo 订单号
* <p>参数说明: String totalAmount 订单总金额
* <p>参数说明: String body 商品描述
* <p>返回说明: Map<String,Object>
* <p>创 建 人: cjb
**/
private Map<String, Object> payment(String notifyUrl, String orderNo, String totalAmount, String body, String openId) {
System.out.println("↓↓↓↓↓↓↓↓↓↓微信支付统一下单参数处理↓↓↓↓↓↓↓↓↓↓");
String unifiedOrderParam = wxpayUtil.getUnifiedOrder(orderNo, totalAmount, notifyUrl, body, openId);
//回调参数
Map<String, Object> receiveMap = new HashMap<>(16);
try {
String xmlStr = HttpUtil.doPostToStr(WechatConfig.pay_url, unifiedOrderParam);
receiveMap = XMLUtil.doXMLParse(xmlStr);
System.out.println("微信返回值==" + receiveMap);
} catch (Exception e) {
e.printStackTrace();
System.out.println("微信支付HTTP请求错误");
return null;
}
//请求返回正常:
if ("SUCCESS".equals(receiveMap.get("return_code"))) {
//业务正常:
if ("SUCCESS".equals(receiveMap.get("result_code"))) {
System.out.println("↓↓↓↓↓↓↓↓↓↓微信支付返回APP参数处理↓↓↓↓↓↓↓↓↓↓");
Map<String, Object> data = new HashMap<>(16);
data.put("data", wxpayUtil.getReturnParam(receiveMap));
return data;
}
System.out.println("微信支付请求业务错误:" + receiveMap.get("err_code_des"));
return null;
}
System.out.println("微信支付请求返回错误:" + receiveMap.get("return_msg"));
return null;
}
/**
* <p>方法说明: TODO 获取价格
* <p>参数说明: String notifyUrl 回调地址
* <p>参数说明: String body 商品描述
* <p>返回说明: Map<String,Object>
* <p>创 建 人: cjb
**/
private BigDecimal getSchoolPrice(Integer type) {
BigDecimal mony = null;
switch (type) {
case 1:
mony = codeMapper.selectMoenyByType(type);
break;
case 2:
mony = codeMapper.selectMoenyByType(type);
break;
default:
mony = new BigDecimal(0);
}
return mony;
}
}
总结:
微信支付流程相近,每种支付都有对应的固定值,结合微信开发文档进行编码,需要的参数以及你需要传的参数上面写的还是比较清楚,重点是商户号一定要关联对应的公众号,分清楚不同的id。。
开发不同的微信场景支付 只需要修改WechatConfig 中的交易类型 在开发文档上面找到对应的,以及必发的请求参数进行修改就行了。