微信小程序支付 java

转自:https://blog.csdn.net/zhourenfei17/article/details/77765585


话不多说,直接开撸。

支付流程步骤:

1)首先调用wx.login方法获取code,通过code获取openid;

2)java后台调用统一下单支付接口(这里会进行第一次签名),用来获取prepay_id;

3)java后台再次调用签名(这里会进行第二次签名),并返回支付需要用使用的参数;

4)小程序前端wx.requestPayment方法发起微信支付;

5)java后台接收来自微信服务器的通知并处理结果。

详细步骤可参考:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_4&index=3

demo链接:   https://pan.baidu.com/s/1v8QWUE1m2EnA4uAoAZtRRQ     密码: cgrt


一、获取openid,

这里的代码可以参考博主的另外一篇文章http://blog.csdn.net/zhourenfei17/article/details/77714600中的 3.1 代码模块,代码先贴上,如果了解更多点击链接查看

小程序端代码

  1. wx.login({
  2. success: function (res) {
  3. var service_url = 'https://???/???/weixin/api/login?code=' + res.code; //需要将服务器域名添加到小程序的request合法域名中,而且必须是https开头
  4. wx.request({
  5. url: l,
  6. data: {},
  7. method: 'GET',
  8. success: function (res) {
  9. console.log(res);
  10. if (res.data != null && res.data != undefined && res.data != '') {
  11. wx.setStorageSync( "openid", res.data.openid); //将获取的openid存到缓存中
  12. }
  13. }
  14. });
  15. }
  16. });


java后端代码
  1. /**
  2. * 小程序后台登录,向微信平台发送获取access_token请求,并返回openId
  3. * @param code
  4. * @return 用户凭证
  5. * @throws WeixinException
  6. * @throws IOException
  7. * @throws JsonMappingException
  8. * @throws JsonParseException
  9. */
  10. @RequestMapping( "login")
  11. @ResponseBody
  12. public Map<String, Object> login(String code, HttpServletRequest request) throws WeixinException, JsonParseException, JsonMappingException, IOException {
  13. if (code == null || code.equals( "")) {
  14. throw new WeixinException( "invalid null, code is null.");
  15. }
  16. Map<String, Object> ret = new HashMap<String, Object>();
  17. //拼接参数
  18. String param = "?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret + "&js_code=" + code;
  19. System.out.println( "https://api.weixin.qq.com/sns/jscode2session" + param);
  20. //创建请求对象
  21. HttpsClient http = new HttpsClient();
  22. //调用获取access_token接口
  23. Response res = http.get( "https://api.weixin.qq.com/sns/jscode2session" + param);
  24. //根据请求结果判定,是否验证成功
  25. JSONObject jsonObj = res.asJSONObject();
  26. if (jsonObj != null) {
  27. Object errcode = jsonObj.get( "errcode");
  28. if (errcode != null) {
  29. //返回异常信息
  30. throw new WeixinException(getCause(Integer.parseInt(errcode.toString())));
  31. }
  32. ObjectMapper mapper = new ObjectMapper();
  33. OAuthJsToken oauthJsToken = mapper.readValue(jsonObj.toJSONString(),OAuthJsToken.class);
  34. ret.put( "openid", oauthJsToken.getOpenid());
  35. }
  36. return ret;
  37. }

二、小程序调用java后端接口,生成最终签名和相关参数小程序端代码:
  1. var that = this;
  2. wx.request({
  3. url: service_url + 'wxPay',
  4. data: { },
  5. method: 'GET',
  6. success: function (res) {
  7. console.log(res);
  8. that.doWxPay(res.data);
  9. }
  10. });

java端代码:
  1. /**
  2. * @Description: 发起微信支付
  3. * @param request
  4. */
  5. public Json wxPay(Integer openid, HttpServletRequest request){
  6. try{
  7. //生成的随机字符串
  8. String nonce_str = StringUtils.getRandomStringByLength( 32);
  9. //商品名称
  10. String body = "测试商品名称";
  11. //获取客户端的ip地址
  12. String spbill_create_ip = IpUtil.getIpAddr(request);
  13. //组装参数,用户生成统一下单接口的签名
  14. Map<String, String> packageParams = new HashMap<String, String>();
  15. packageParams.put( "appid", WxPayConfig.appid);
  16. packageParams.put( "mch_id", WxPayConfig.mch_id);
  17. packageParams.put( "nonce_str", nonce_str);
  18. packageParams.put( "body", body);
  19. packageParams.put( "out_trade_no", "123456789"); //商户订单号
  20. packageParams.put( "total_fee", "1"); //支付金额,这边需要转成字符串类型,否则后面的签名会失败
  21. packageParams.put( "spbill_create_ip", spbill_create_ip);
  22. packageParams.put( "notify_url", WxPayConfig.notify_url); //支付成功后的回调地址
  23. packageParams.put( "trade_type", WxPayConfig.TRADETYPE); //支付方式
  24. packageParams.put( "openid", openid);
  25. String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
  26. //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
  27. String mysign = PayUtil.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();
  28. //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
  29. String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"
  30. + "<body><![CDATA[" + body + "]]></body>"
  31. + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"
  32. + "<nonce_str>" + nonce_str + "</nonce_str>"
  33. + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"
  34. + "<openid>" + order.getOpenId() + "</openid>"
  35. + "<out_trade_no>" + order.getOrderNo() + "</out_trade_no>"
  36. + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
  37. + "<total_fee>" + order.getPayMoney() + "</total_fee>"
  38. + "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"
  39. + "<sign>" + mysign + "</sign>"
  40. + "</xml>";
  41. System.out.println( "调试模式_统一下单接口 请求XML数据:" + xml);
  42. //调用统一下单接口,并接受返回的结果
  43. String result = PayUtil.httpRequest(WxPayConfig.pay_url, "POST", xml);
  44. System.out.println( "调试模式_统一下单接口 返回XML数据:" + result);
  45. // 将解析结果存储在HashMap中
  46. Map map = PayUtil.doXMLParse(result);
  47. String return_code = (String) map.get( "return_code"); //返回状态码
  48. Map<String, Object> response = new HashMap<String, Object>(); //返回给小程序端需要的参数
  49. if(return_code== "SUCCESS"||return_code.equals(return_code)){
  50. String prepay_id = (String) map.get( "prepay_id"); //返回的预付单信息
  51. response.put( "nonceStr", nonce_str);
  52. response.put( "package", "prepay_id=" + prepay_id);
  53. Long timeStamp = System.currentTimeMillis() / 1000;
  54. response.put( "timeStamp", timeStamp + ""); //这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误
  55. //拼接签名需要的参数
  56. String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;
  57. //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
  58. String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();
  59. response.put( "paySign", paySign);
  60. }
  61. response.put( "appid", WxPayConfig.appid);
  62. return response;
  63. } catch(Exception e){
  64. e.printStackTrace();
  65. }
  66. return null;
  67. }
  68. /**
  69. * StringUtils工具类方法
  70. * 获取一定长度的随机字符串,范围0-9,a-z
  71. * @param length:指定字符串长度
  72. * @return 一定长度的随机字符串
  73. */
  74. public static String getRandomStringByLength(int length) {
  75. String base = "abcdefghijklmnopqrstuvwxyz0123456789";
  76. Random random = new Random();
  77. StringBuffer sb = new StringBuffer();
  78. for ( int i = 0; i < length; i++) {
  79. int number = random.nextInt(base.length());
  80. sb.append(base.charAt(number));
  81. }
  82. return sb.toString();
  83. }
  84. /**
  85. * IpUtils工具类方法
  86. * 获取真实的ip地址
  87. * @param request
  88. * @return
  89. */
  90. public static String getIpAddr(HttpServletRequest request) {
  91. String ip = request.getHeader( "X-Forwarded-For");
  92. if(StringUtils.isNotEmpty(ip) && ! "unKnown".equalsIgnoreCase(ip)){
  93. //多次反向代理后会有多个ip值,第一个ip才是真实ip
  94. int index = ip.indexOf( ",");
  95. if(index != - 1){
  96. return ip.substring( 0,index);
  97. } else{
  98. return ip;
  99. }
  100. }
  101. ip = request.getHeader( "X-Real-IP");
  102. if(StringUtils.isNotEmpty(ip) && ! "unKnown".equalsIgnoreCase(ip)){
  103. return ip;
  104. }
  105. return request.getRemoteAddr();
  106. }

WxPayConfig小程序配置文件
  1. /**
  2. * 小程序微信支付的配置文件
  3. * @author
  4. *
  5. */
  6. public class WxPayConfig {
  7. //小程序appid
  8. public static final String appid = "";
  9. //微信支付的商户id
  10. public static final String mch_id = "";
  11. //微信支付的商户密钥
  12. public static final String key = "";
  13. //支付成功后的服务器回调url
  14. public static final String notify_url = "https://??/??/weixin/api/wxNotify";
  15. //签名方式,固定值
  16. public static final String SIGNTYPE = "MD5";
  17. //交易类型,小程序支付的固定值为JSAPI
  18. public static final String TRADETYPE = "JSAPI";
  19. //微信统一下单接口地址
  20. public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  21. }

PayUtils工具类
  1. import java.io.BufferedReader;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.security.SignatureException;
  11. import java.util.ArrayList;
  12. import java.util.Collections;
  13. import java.util.HashMap;
  14. import java.util.Iterator;
  15. import java.util.List;
  16. import java.util.Map;
  17. import org.apache.commons.codec.digest.DigestUtils;
  18. import org.jdom.Document;
  19. import org.jdom.Element;
  20. import org.jdom.JDOMException;
  21. import org.jdom.input.SAXBuilder;
  22. public class PayUtil {
  23. /**
  24. * 签名字符串
  25. * @param text需要签名的字符串
  26. * @param key 密钥
  27. * @param input_charset编码格式
  28. * @return 签名结果
  29. */
  30. public static String sign(String text, String key, String input_charset) {
  31. text = text + "&key=" + key;
  32. return DigestUtils.md5Hex(getContentBytes(text, input_charset));
  33. }
  34. /**
  35. * 签名字符串
  36. * @param text需要签名的字符串
  37. * @param sign 签名结果
  38. * @param key密钥
  39. * @param input_charset 编码格式
  40. * @return 签名结果
  41. */
  42. public static boolean verify(String text, String sign, String key, String input_charset) {
  43. text = text + key;
  44. String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
  45. if (mysign.equals(sign)) {
  46. return true;
  47. } else {
  48. return false;
  49. }
  50. }
  51. /**
  52. * @param content
  53. * @param charset
  54. * @return
  55. * @throws SignatureException
  56. * @throws UnsupportedEncodingException
  57. */
  58. public static byte[] getContentBytes(String content, String charset) {
  59. if (charset == null || "".equals(charset)) {
  60. return content.getBytes();
  61. }
  62. try {
  63. return content.getBytes(charset);
  64. } catch (UnsupportedEncodingException e) {
  65. throw new RuntimeException( "MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
  66. }
  67. }
  68. private static boolean isValidChar(char ch) {
  69. if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
  70. return true;
  71. if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
  72. return true; // 简体中文汉字编码
  73. return false;
  74. }
  75. /**
  76. * 除去数组中的空值和签名参数
  77. * @param sArray 签名参数组
  78. * @return 去掉空值与签名参数后的新签名参数组
  79. */
  80. public static Map<String, String> paraFilter(Map<String, String> sArray) {
  81. Map<String, String> result = new HashMap<String, String>();
  82. if (sArray == null || sArray.size() <= 0) {
  83. return result;
  84. }
  85. for (String key : sArray.keySet()) {
  86. String value = sArray.get(key);
  87. if (value == null || value.equals( "") || key.equalsIgnoreCase( "sign")
  88. || key.equalsIgnoreCase( "sign_type")) {
  89. continue;
  90. }
  91. result.put(key, value);
  92. }
  93. return result;
  94. }
  95. /**
  96. * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
  97. * @param params 需要排序并参与字符拼接的参数组
  98. * @return 拼接后字符串
  99. */
  100. public static String createLinkString(Map<String, String> params) {
  101. List<String> keys = new ArrayList<String>(params.keySet());
  102. Collections.sort(keys);
  103. String prestr = "";
  104. for ( int i = 0; i < keys.size(); i++) {
  105. String key = keys.get(i);
  106. String value = params.get(key);
  107. if (i == keys.size() - 1) { // 拼接时,不包括最后一个&字符
  108. prestr = prestr + key + "=" + value;
  109. } else {
  110. prestr = prestr + key + "=" + value + "&";
  111. }
  112. }
  113. return prestr;
  114. }
  115. /**
  116. *
  117. * @param requestUrl请求地址
  118. * @param requestMethod请求方法
  119. * @param outputStr参数
  120. */
  121. public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
  122. // 创建SSLContext
  123. StringBuffer buffer = null;
  124. try{
  125. URL url = new URL(requestUrl);
  126. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  127. conn.setRequestMethod(requestMethod);
  128. conn.setDoOutput( true);
  129. conn.setDoInput( true);
  130. conn.connect();
  131. //往服务器端写内容
  132. if( null !=outputStr){
  133. OutputStream os=conn.getOutputStream();
  134. os.write(outputStr.getBytes( "utf-8"));
  135. os.close();
  136. }
  137. // 读取服务器端返回的内容
  138. InputStream is = conn.getInputStream();
  139. InputStreamReader isr = new InputStreamReader(is, "utf-8");
  140. BufferedReader br = new BufferedReader(isr);
  141. buffer = new StringBuffer();
  142. String line = null;
  143. while ((line = br.readLine()) != null) {
  144. buffer.append(line);
  145. }
  1.                 br.close();
  2. } catch(Exception e){
  3. e.printStackTrace();
  4. }
  5. return buffer.toString();
  6. }
  7. public static String urlEncodeUTF8(String source){
  8. String result=source;
  9. try {
  10. result=java.net.URLEncoder.encode(source, "UTF-8");
  11. } catch (UnsupportedEncodingException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. }
  15. return result;
  16. }
  17. /**
  18. * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
  19. * @param strxml
  20. * @return
  21. * @throws JDOMException
  22. * @throws IOException
  23. */
  24. public static Map doXMLParse(String strxml) throws Exception {
  25. if( null == strxml || "".equals(strxml)) {
  26. return null;
  27. }
  28. Map m = new HashMap();
  29. InputStream in = String2Inputstream(strxml);
  30. SAXBuilder builder = new SAXBuilder();
  31. Document doc = builder.build(in);
  32. Element root = doc.getRootElement();
  33. List list = root.getChildren();
  34. Iterator it = list.iterator();
  35. while(it.hasNext()) {
  36. Element e = (Element) it.next();
  37. String k = e.getName();
  38. String v = "";
  39. List children = e.getChildren();
  40. if(children.isEmpty()) {
  41. v = e.getTextNormalize();
  42. } else {
  43. v = getChildrenText(children);
  44. }
  45. m.put(k, v);
  46. }
  47. //关闭流
  48. in.close();
  49. return m;
  50. }
  51. /**
  52. * 获取子结点的xml
  53. * @param children
  54. * @return String
  55. */
  56. public static String getChildrenText(List children) {
  57. StringBuffer sb = new StringBuffer();
  58. if(!children.isEmpty()) {
  59. Iterator it = children.iterator();
  60. while(it.hasNext()) {
  61. Element e = (Element) it.next();
  62. String name = e.getName();
  63. String value = e.getTextNormalize();
  64. List list = e.getChildren();
  65. sb.append( "<" + name + ">");
  66. if(!list.isEmpty()) {
  67. sb.append(getChildrenText(list));
  68. }
  69. sb.append(value);
  70. sb.append( "</" + name + ">");
  71. }
  72. }
  73. return sb.toString();
  74. }
  75. public static InputStream String2Inputstream(String str) {
  76. return new ByteArrayInputStream(str.getBytes());
  77. }
  78. }

三、小程序端发起最终支付,调用微信付款
  1. doWxPay(param){
  2. //小程序发起微信支付
  3. wx.requestPayment({
  4. timeStamp: param.data.timeStamp, //记住,这边的timeStamp一定要是字符串类型的,不然会报错,我这边在java后端包装成了字符串类型了
  5. nonceStr: param.data.nonceStr,
  6. package: param.data.package,
  7. signType: 'MD5',
  8. paySign: param.data.paySign,
  9. success: function (event) {
  10. // success
  11. console.log(event);
  12. wx.showToast({
  13. title: '支付成功',
  14. icon: 'success',
  15. duration: 2000
  16. });
  17. },
  18. fail: function (error) {
  19. // fail
  20. console.log( "支付失败")
  21. console.log(error)
  22. },
  23. complete: function () {
  24. // complete
  25. console.log( "pay complete")
  26. }
  27. });
  28. }

四、微信服务器通知java后端

  1. /**
  2. * @Description:微信支付
  3. * @return
  4. * @throws Exception
  5. */
  6. @RequestMapping(value= "/wxNotify")
  7. @ResponseBody
  8. public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
  9. BufferedReader br = new BufferedReader( new InputStreamReader((ServletInputStream)request.getInputStream()));
  10. String line = null;
  11. StringBuilder sb = new StringBuilder();
  12. while((line = br.readLine()) != null){
  13. sb.append(line);
  14. }
  15. br.close();
  16. //sb为微信返回的xml
  17. String notityXml = sb.toString();
  18. String resXml = "";
  19. System.out.println( "接收到的报文:" + notityXml);
  20. Map map = PayUtil.doXMLParse(notityXml);
  21. String returnCode = (String) map.get( "return_code");
  22. if( "SUCCESS".equals(returnCode)){
  23. //验证签名是否正确
  24. Map<String, String> validParams = PayUtil.paraFilter(map); //回调验签时需要去除sign和空值参数
  25. String validStr = PayUtil.createLinkString(validParams); //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
  26. String sign = PayUtil.sign(validStr, WxPayConfig.key, "utf-8").toUpperCase(); //拼装生成服务器端验证的签名
  27. //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
  28. if(sign.equals(map.get( "sign"))){
  29. /**此处添加自己的业务逻辑代码start**/
  30. /**此处添加自己的业务逻辑代码end**/
  31. //通知微信服务器已经支付成功
  32. resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
  33. + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
  34. }
  35. } else{
  36. resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
  37. + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
  38. }
  39. System.out.println(resXml);
  40. System.out.println( "微信支付回调数据结束");
  41. BufferedOutputStream out = new BufferedOutputStream(
  42. response.getOutputStream());
  43. out.write(resXml.getBytes());
  44. out.flush();
  45. out.close();
  46. }

猜你喜欢

转载自blog.csdn.net/y19910825/article/details/80965898