第三方支付4(前端实现支付)

                                                       前端实现微信支付

首先,我们贴出调用支付接口的H5页面,当然,在这个页面之前,还需要做很多其他的操作,我们一步一步的来。

坑爹的官方文档给了两个不同的支付接口,在微信公众平台开发中文档的“微信JS-SDK说明文档”中,给出的支付方式是下面被屏蔽的那一部分,而在商户平台的“H5调起支付API”中,又给了一份不同的接口,即下面未屏蔽正常使用的接口。关于坑爹的微信提供了两个不同的支付接口,网上搜索结果也是众说纷纷,所以,只有自己试了。当然,为了简单,我直接试了下面这一种,然后奇迹般的成功了。

?
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
 
< html >
   < head >
     < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >
     < title >微信网页支付 title >
    
    
     < script type = "text/javascript" >
       /* wx.config({
         debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
         appId: appid, // 必填,公众号的唯一标识
         timestamp: timestamp, // 必填,生成签名的时间戳
         nonceStr: nonceStr, // 必填,生成签名的随机串
         signature: '',// 必填,签名,见附录1
         jsApiList: [chooseWXPay] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
       }); */
      
       // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作
       //所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行
       //wx.ready(function(){
         //参数是后台传过来的,签名加密,随机数,时间戳等全部后台处理好
         var appId="${appId}";
         var timeStamp="${timeStamp}";
         var nonceStr="${nonceStr}";
         var prepay_id="${prepay_id}";//之前参数名叫package,对应api接口,因为package是关键字,被坑了一次
         var sign="${paySign}";
         //支付接口
         function onBridgeReady(){
             WeixinJSBridge.invoke(
               'getBrandWCPayRequest', {
                 "appId" : appId,   //公众号名称,由商户传入 
                 "timeStamp" : timeStamp, //时间戳,自1970年以来的秒数 (java需要处理成10位才行,又一坑)
                 "nonceStr" : nonceStr, //随机串
                 "package" : prepay_id, //拼装好的预支付标示
                 "signType" : "MD5",//微信签名方式
                 "paySign" : sign //微信签名
               },
               function(res){
                 //使用以下方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回  ok,但并不保证它绝对可靠。
                 if(res.err_msg == "get_brand_wcpay_request:ok" ) {   
                   alert("支付成功");       
                 }else{
                   alert("支付失败");
                 }
               }
             ); 
         }
         if (typeof(WeixinJSBridge) == "undefined"){
           if( document.addEventListener ){
             document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
           }else if (document.attachEvent){
             document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
             document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
           }
         }else{
           onBridgeReady();
         }
       //});
       //究竟哪个是支付接口
       /* wx.chooseWXPay({
         timestamp: timestamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
         nonceStr: nonceStr, // 支付签名随机串,不长于 32 位
         package: 'prepay_id', // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***)
         signType: 'MD5', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
         paySign: sign, // 支付签名
         success: function (res) {
           // 支付成功后的回调函数
           //使用以下方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回  ok,但并不保证它绝对可靠。
           if(res.err_msg == "get_brand_wcpay_request:ok" ) {   
                        
          
         }
       }); */
     script >
   head >
   < body >
      
   body >
html >

上面h5页面中,支付接口所需的参数都是由后台传过来的,除此之外,在进行上面一步之前,我们还需要获取一个预支付标识,下面贴上后台传参,及获取预支付标识和参数加密等方法(获取预支付标识之前需要网页授权获取用户openid,鉴于这个比较简单,所以不贴代码了)

首先是后台参数封装并对其签名(关键部分代码):

?
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
if (payway.equals( "1" )){
       System.out.println( "----------支付宝支付-------------" );
       request.setAttribute( "WIDout_trade_no" , WIDout_trade_no); //订单号
       request.setAttribute( "WIDsubject" , WIDsubject); //订单名称
       request.setAttribute( "WIDtotal_fee" , WIDtotal_fee); //付款金额
       request.setAttribute( "WIDshow_url" , WIDshow_url); //商品链接
       request.setAttribute( "WIDbody" , "" ); //商品描述,可空
       return "alipayapi" ;
     } else if (payway.equals( "2" )){
       System.out.println( "----------微信支付-------------" );
       //1、通过网页授权接口,获取到的openid
       String openid=request.getSession().getAttribute( "openid" )+ "" ;
       //处理价格单位为:分(请自行处理)
       WIDtotal_fee= "1" ;
       String preid=getPrepayid(WIDout_trade_no, WIDtotal_fee, openid); //获取预支付标示
       System.out.println( "预支付标示:----------------" +preid);
       //APPID
       String appId=Common.appid;
       request.setAttribute( "appId" , appId);
       //时间戳
       String timeStamp=(System.currentTimeMillis()/ 1000 )+ "" ;
       request.setAttribute( "timeStamp" , timeStamp);
       //随机字符串
       String nonceStr=Common.randString( 16 ).toString();
       request.setAttribute( "nonceStr" , nonceStr);
       //预支付标识
       request.setAttribute( "prepay_id" , "prepay_id=" +preid);
       //加密方式
       request.setAttribute( "signType" , "MD5" );
        
       //组装map用于生成sign
       Map map= new HashMap();
       map.put( "appId" , appId);
       map.put( "timeStamp" , timeStamp);
       map.put( "nonceStr" , nonceStr);
       map.put( "package" , "prepay_id=" +preid);
       map.put( "signType" , "MD5" );
        
       request.setAttribute( "paySign" , Common.sign(map, Common.MchSecret)); //签名
       return "weixinpay" ;
     } else {
       return "error" ;
     }

接下是获取预支付标识的方法getPrepayid:

?
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
/**
    * 微信统一下单接口,获取预支付标示prepay_id
    * @param out_trade_no1 商户订单号
    * @param total_fee1 订单金额(单位:分)
    * @param openid1 网页授权取到的openid
    * @return
    */
   @ResponseBody
   public String getPrepayid(String out_trade_no1,String total_fee1,String openid1){
      
     String result = "" ;
      
     String appid = Common.appid;
     String mch_id = Common.mch_id;
     String nonce_str = Common.randString( 16 ); //生成随机数,可直接用系统提供的方法
     String body = "E光学-商品订单" ;
     String out_trade_no = out_trade_no1;
     String total_fee = total_fee1;
     String spbill_create_ip = "xxx.xxx.38.47" ; //用户端ip,这里随意输入的
     String notify_url = "http://www.xxxxxxx.cn/egxwx/wxpay_notify_url.jsp" ;//支付回调地址
     String trade_type = "JSAPI" ;
     String openid = openid1;
      
     HashMap map = new HashMap();
     map.put( "appid" , appid);
     map.put( "mch_id" , mch_id);
     map.put( "attach" , "支付测试" );
     map.put( "device_info" , "WEB" );
     map.put( "nonce_str" , nonce_str);
     map.put( "body" , body);
     map.put( "out_trade_no" , out_trade_no);
     map.put( "total_fee" , total_fee);
     map.put( "spbill_create_ip" , spbill_create_ip);
     map.put( "trade_type" , trade_type);
     map.put( "notify_url" , notify_url);
     map.put( "openid" , openid);
     String sign = Common.sign(map, Common.MchSecret); //参数加密
     System.out.println( "sign秘钥:-----------" +sign);
     map.put( "sign" , sign);
     //组装xml(wx就这么变态,非得加点xml在里面)
     String content=Common.MapToXml(map);
     //System.out.println(content);
     String PostResult=HttpClient.HttpsPost( "https://api.mch.weixin.qq.com/pay/unifiedorder" , content);
     JSONObject jsonObject=XmlUtil.XmlToJson(PostResult); //返回的的结果
     if (jsonObject.getString( "return_code" ).equals( "SUCCESS" )&&jsonObject.getString( "result_code" ).equals( "SUCCESS" )){
       result=jsonObject.get( "prepay_id" )+ "" ; //这就是预支付id
     }
     return result;
   }

接下是签名的方法(MD5加密是调用微信一个jar里面的,你也可以自己写一个,网上很多参考):

?
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
    * 生成签名sign
    * 第一步:非空参数值的参数按照参数名ASCII码从小到大排序,按照键值对的形式。生成字符串StringA
    * stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA";
    * 第二部:拼接API密钥,这里的秘钥是微信商户平台的秘钥,是自己设置的,不是公众号的秘钥
    * stringSignTemp="stringA&key=192006250b4c09247ec02edce69f6a2d"
    * 第三部:MD5加密
    * sign=MD5(stringSignTemp).toUpperCase()="9A0A8659F005D6984697E2CA0A9CF3B7"
    *
    * @param map 不包含空字符串的map
    * @return
    */
   public static String sign(Map map,String key) {
     //排序
     String sort=sortParameters(map);
     //拼接API秘钥
     sort=sort+ "&key=" +key;
     //System.out.println(sort);
     //MD5加密
     String sign=MD5.MD5Encode(sort).toUpperCase();
     return sign;
   }
    
   /**
    * 对参数列表进行排序,并拼接key=value&key=value形式
    * @param map
    * @return
    */
   private static String sortParameters(Map map) {
     Set keys = map.keySet();
     List paramsBuf = new ArrayList();
     for (String k : keys) {
       paramsBuf.add((k + "=" + getParamString(map, k)));
     }
     // 对参数排序
     Collections.sort(paramsBuf);
     String result= "" ;
     int count=paramsBuf.size();
     for ( int i= 0 ;i
       if (i<(count- 1 )){
         result+=paramsBuf.get(i)+ "&" ;
       } else {
         result+=paramsBuf.get(i);
       }
     }
     return result;
   }
   /**
    * 返回key的值
    * @param map
    * @param key
    * @return
    */
   private static String getParamString(Map map, String key) {
     String buf = "" ;
     if (map.get(key) instanceof String[]) {
       buf = ((String[]) map.get(key))[ 0 ];
     } else {
       buf = (String) map.get(key);
     }
     return buf;
   }
   /**
    * 字符串列表从大到小排序
    * @param data
    * @return
    */
   private static List sort(List data) {
     Collections.sort(data, new Comparator() {
       public int compare(String obj1, String obj2) {
         return obj1.compareTo(obj2);
       }
     });
     return data;
   }

Map转XML的方法:

?
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
/**
    * Map转Xml
    * @param arr
    * @return
    */
   public static String MapToXml(Map arr) {
     String xml = "" ;
     Iterator> iter = arr.entrySet().iterator();
     while (iter.hasNext()) {
       Entry entry = iter.next();
       String key = entry.getKey();
       String val = entry.getValue();
       if (IsNumeric(val)) {
         xml += "<" + key + ">" + val + " + key + ">" ;
       } else
         xml += "<" + key + "> + val + "]]> + key + ">" ;
     }
     xml += "" ;
     return xml;
   }
   private static boolean IsNumeric(String str) {
     if (str.matches( "\\d *" )) {
       return true ;
     } else {
       return false ;
     }
   }

        

第三方接口调用        

你可能感兴趣的:(第三方接口调用)