⼩程序⽀付功能—Java代码实现摘要
本篇⽂章带⼤家实现⼩程序⽀付,有需要的伙伴可以参考借鉴⼀下。
注意事项
开发⼩程序⽀付功能前,需要登录⼩程序后台开通⽀付功能
步骤
第⼀步:获取⽀付所需参数
获取⽀付时所需openId参考此篇博⽂:
⼩程序页⾯(wxPay.js)代码:
写文章的小程序后端Java代码:wx .login ({  success : res => {    // 发送 de 到后台换取 openId, sessionKey, unionId      wx .request ({      url : that .data .url + '/mini_Weixin_getOpenId.action',      data :{"code":res .code },      method :'GET',      header : {        'content-type': 'application/json'      },      success : function  (res ) {          openId = res .data ;          wx .request ({            url : that .data .url + 'xxx_getPayParameter.action',            data :{"openId":openId ,"totalAmount":payData .payAmount ,"orderId":payData .orderId },            method :'GET',            header : {              'content-type': 'application/json'            },            success : function  (res ) {              that .goPay (res );  //调⽤⽀付                          }          })      }    })  } })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28/** * ⼩程序统⼀下单接⼝,并返回相关参数 */public  String getPayParameter (){  try  {  String notify_url = "⽀付成功回调地址";  reqIp = getIpAddress ();  JSONObject json = new  JSONObject ();  String totalFeeStr = "";//原始的⽀付⾦额,单位元  Float totalFee = 0.0f ;  //随机数  String nonce_str = UUID .randomUUID ().toString ().replaceAll ("-", "");  //商品描述  String body = "测试";  //商户订单号  String out_trade_no = orderId ;  //总⾦额  Integer total_fee = 0;//转化成单位,元--分    String time_start =DateUtil .formatDateTime ();  double  totalAmount_all = 0;  logger .info ("/ns/toPay=reqIP==="+reqIp );  totalAmount_all = Arith .add (totalAmount_all , Double .valueOf (totalAmount ));  totalFeeStr = Double .toString (totalAmount_all );  totalFee = new  Float (totalAmount_all );  total_fee = Math .round (totalFee *100);//转化成单位,元--分  logger .info ("/ns/toPay=totalFeeStr==="+totalFeeStr );  logger .info ("/ns/toPay=totalFee==="+totalFee );  logger .info ("/ns/toPay=total_fee==="+total_fee );  logger .info ("/ns/toPay=body==="+body );1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//获取统⼀下单需要的openid  logger .info ("weixToPay.openId:===@==" + openId );  try  {  if (openId ==null ||"".equals (openId )){    logger .info ("获取统⼀下单需要的openid 失败!");    return  json .toString ();  }  } catch  (Exception e ) {  e .printStackTrace ();  return  null ;  }  //获取sign  SortedMap <String , String > packageParams = new  TreeMap <String , String >();  packageParams .put ("appid
", "⼩程序appId");  packageParams .put ("mch_id","商户号");  packageParams .put ("nonce_str", nonce_str );  packageParams .put ("body", body );  packageParams .put ("out_trade_no", out_trade_no );  packageParams .put ("total_fee", total_fee +"");  packageParams .put ("spbill_create_ip", reqIp );  packageParams .put ("notify_url", notify_url );  packageParams .put ("trade_type", "JSAPI");    packageParams .put ("openid", openId );    RequestHandler reqHandler = new  RequestHandler (this .getRequest (), this .getResponse ());  reqHandler .init ("⼩程序appId", "⼩程序appsecret", "商户密钥");    String sign = reqHandler .createSign (packageParams );  //System.out.println("sign:===@=="+sign);  String xml ="<xml>"+    "<appid>"+appId +"</appid>"+    "<mch_id>"+商户号+"</mch_id>"+    "<nonce_str>"+nonce_str +"</nonce_str>"+    "<sign>"+sign +"</sign>"+    "<body><![CDATA["+body +"]]></body>"+    "<out_trade_no>"+out_trade_no +"</out_trade_no>"+    "<total_fee>"+total_fee +"</total_fee>"+    "<spbill_create_ip>"+reqIp +"</spbill_create_ip>"+  //终端ip    "<notify_url>"+notify_url +"</notify_url>"+    "<trade_type>JSAPI</trade_type>"+    "<openid>"+openId +"</openid>"+    "</xml>";  logger .info ("xml :===@=="+xml );    //获取预⽀付prepay_id  String createOrderURL = "h.weixin.qq/pay/unifiedorder";  String prepay_id ="";  try  {  prepay_id = MiniUtil .getPayNo (createOrderURL , xml );  logger .info ("获取预⽀付prepay_id:===@==" + prepay_id );  if (prepay_id .equals ("")){    json .put ("orderId", orderId );    json .put ("orderName", body );    json .put
("totalFee", totalFeeStr );    json .put ("createTime", time_start );    json .put ("ErrorMsg", "统⼀⽀付接⼝获取预⽀付订单出错");    return  json .toString ();      }  } catch  (Exception e1) {    e1.printStackTrace ();34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
}  SortedMap <String , String > finalpackage = new  TreeMap <String , String >();  String timestamp =
String .valueOf (System .currentTimeMillis () / 1000);  String packages = "prepay_id="+prepay_id ;  finalpackage .put ("appId", "appId");  finalpackage .put ("timeStamp", timestamp );  finalpackage .put ("nonceStr", nonce_str );  finalpackage .put ("package", packages );  finalpackage .put ("signType", "MD5");  String finalsign = reqHandler .createSign (finalpackage );  json .put ("appid", "appId");  json .put ("timeStamp", timestamp );  json .put ("nonceStr", nonce_str );  json .put ("createTime", time_start );  json .put ("package", packages );  json .put ("paySign", finalsign );  json .put ("orderId", orderId );  json .put ("payPrice", total_fee );  //⽀付⾦额,单位分  json .put ("totalFeeStr", totalFeeStr ); //原始的⽀付⾦额,单位元  return  json .toString ();  } catch  (NumberFormatException e ) {  e .printStackTrace ();  logger .info (e );  return  null ; }}/*** 加法运算。* @param v1 被加数* @param v2 加数* @return 两个参数的和*/public  static  double  add (double  v1,double  v2){    BigDecimal b1 = new  BigDecimal (Double .toString (v1));    BigDecimal b2 = new  BigDecimal (Double .toString (v2));    return  b1.add (b2).doubleValue ();}/*** 获取⽀付时所需Ip 地址* @return */public  String getIpAddress () {  HttpServletRequest request = this .getRequest ();      String ip = request .getHeader ("x-forwarded-for");        if  (ip == null || ip .length () == 0 || "unknown".equalsIgnoreCase (ip )) {            ip = request .getHeader ("Proxy-Client-IP");        }        if  (ip == null || ip .length () == 0 || "unknown".equalsIgnoreCase (ip )) {            ip = request .getHeader ("WL-Proxy-Client-IP");        }        if  (ip == null || ip .length () == 0 || "unknown".equalsIgnoreCase (ip )) {            ip = request .getHead
er ("HTTP_CLIENT_IP");        }        if  (ip == null || ip .length () == 0 || "unknown".equalsIgnoreCase (ip )) {            ip = request .getHeader ("HTTP_X_FORWARDED_FOR");        }        if  (ip == null || ip .length () == 0 || "unknown".equalsIgnoreCase (ip )) {            ip = request .getRemoteAddr ();        }        return  ip ;  99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
RequestHandler ⼯具类:
164public  class  RequestHandler {/** Token 获取⽹关地址地址 */ private  String tokenUrl ; /** 预⽀付⽹关url 地址 */ private  String gateUrl ; /** 查询⽀付通知⽹关URL */ private  String notifyUrl ; /** 商户参数 */ private  String appid ; private  String appkey ; private  String partnerkey ; private  String appsecret ; private  String key ; /** 请求的参数 */ private  SortedMap parameters ; /** Token */ private  String Token ; private  String charset ; /** debug 信息 */ private  String debugInfo ; private  String last_errcode ; private  HttpServletRequest request ; private  HttpServletResponse response ; /**  * 初始构造函数。  *  * @return  */ public  RequestHandler (HttpServletRequest request ,  HttpServletResponse response ) {  this .last_errcode = "0";  this .request = request ;  this .response = response ;  //this.charset = "GBK";  this .charset = "UTF-8";  this .parameters = new  TreeMap ();  // 验证notify ⽀付订单⽹关  notifyUrl = "gw.tenpay/l";  } /**  * 初始化函数。  */ public  void  init (String app_id , String app_secret , String partner_key ) {  this .last_errcode = "0";  this .Token = "token_";  this .debugInfo = "";  this .appid = app_id ;  this .partnerkey = partner_key ;  this .appsecret = app_secret ;  this .key = partner_key ; } public  void  init () { }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。