1. 程式人生 > >java服務端微信小程式支付demo

java服務端微信小程式支付demo

一丶項目錄結構 demo下載地址 小程式支付demo下載 在這裡插入圖片描述 二丶實現步驟 1.在小程式中獲取使用者的登入資訊,成功後可以獲取到使用者的程式碼值 2.在使用者自己的服務端請求微信獲取使用者的OpenID介面,成功後可以電子雜誌使用者的OpenID的值 微信官方API地址:點選開啟連結 3 。在使用者自己的伺服器上面請求微信的統一下單介面,下單成功後可以獲取prepay_id值微信官方API地址:點選開啟連結 4.在微信小程式中支付訂單,最終實現微信的支付功能

微信官方API地址:點選開啟連結 在這裡插入圖片描述

1,下面我們就開始詳細的介紹一下微信支付的整個流程: 首先是獲取使用者的資訊,也就是小程式中的登入介面:

//app.js
應用程式({
  onLaunch:function(){
    wx.login({
      成功:功能(res){
        if(res.code){
          //發起網路請求
          wx.request({
            網址:'https://test.com/onLogin',
            資料:{
              程式碼:res.code
            }
          })
        } else {
          console.log('獲取使用者登入態失敗!'+ res.errMsg)
        }
      }
    });
  }
})

2,contrller層實現登陸方法方法

/ **
 * @Description:本示例僅供參考,請根據自己的使用情景進行修改
 * @Date:2018/7/17
 * @Author:wcf
 * /
@RequestMapping( “/衛新”)
@RestController
公共類WeixinController擴充套件了WeixinSupport {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final String appid =“”; //微信小程式的appid
    private static final String secret =“”; //微信小程式金鑰
    private static final String grant_type =“”;

    / **
     *小程式後臺登入,向微信平臺傳送獲取access_token請求,並返回openId
     *
     * @param程式碼
     * @return openid
     * @throws WeixinException
     * @throws IOException
     * @since Weixin4J 1.0.0
     * /
    @RequestMapping( “登入”)
    public Map <String,Object> login(字串程式碼,HttpServletRequest請求)丟擲WeixinException,IOException {
        if(code == null || code.equals(“”)){
            丟擲新的WeixinException(“無效null,程式碼為空。”);
        }

        Map <String,Object> ret = new HashMap <String,Object>();
        //拼接引數
        String param =“?grant_type =”+ grant_type +“&appid =”+ appid +“&secret =”+ secret +“&js_code =”+ code;

        //建立請求物件
        HttpsClient http = new HttpsClient();
        //呼叫獲取的access_token介面
        響應res = http.get(“https://api.weixin.qq.com/sns/jscode2session”+ param);
        //根據請求結果判定,是否驗證成功
        JSONObject jsonObj = res.asJSONObject();
        if(jsonObj!= null){
            Object errcode = jsonObj.get(“errcode”);
            if(errcode!= null){
                //返回異常資訊
                丟擲新的WeixinException(getCause(Integer.parseInt(errcode.toString())));
            }

            ObjectMapper mapper = new ObjectMapper();
            OAuthJsToken oauthJsToken = mapper.readValue(jsonObj.toJSONString(),OAuthJsToken.class);

            logger.info(“openid =”+ oauthJsToken.getOpenid());
            ret.put(“openid”,oauthJsToken.getOpenid());
        }
        返回;
    }

3,發起微信支付請求

   / **
     * @Description:發起微信支付
     * @param openid
     * @param請求
     * @author:wcf
     * @date:2018年7月17日
     * /
    @RequestMapping( “wxPay”)
    public Json wxPay(String openid,HttpServletRequest request){
        Json json = new Json();
        嘗試{
            //生成的隨機字串
            String nonce_str = StringUtils.getRandomStringByLength(32);
            //商品名稱
            String body =“測試商品名稱”;
            //獲取本機的IP地址
            String spbill_create_ip = IpUtils.getIpAddr(request);

            String orderNo =“123456788”;
            String money =“1”; //支付金額,單位:分,這邊需要轉成字串型別,否則後面的簽名會失敗

            Map <String,String> packageParams = new HashMap <String,String>();
            packageParams.put(“appid”,WxPayConfig.appid);
            packageParams.put(“mch_id”,WxPayConfig.mch_id);
            packageParams.put(“nonce_str”,nonce_str);
            packageParams.put(“body”,body);
            packageParams.put(“out_trade_no”,orderNo); //商戶訂單號
            packageParams.put(“total_fee”,money); //支付金額,這邊需要轉成字串型別,否則後面的簽名會失敗
            packageParams.put(“spbill_create_ip”,spbill_create_ip);
            packageParams.put(“notify_url”,WxPayConfig.notify_url);
            packageParams.put(“trade_type”,WxPayConfig.TRADETYPE);
            packageParams.put(“openid”,openid);

            //除去陣列中的空值和簽名引數
            packageParams = PayUtil.paraFilter(packageParams);
            String prestr = PayUtil.createLinkString(packageParams); //把陣列所有元素,按照“引數=引數值”的模式用“&”字元拼接成字串

            // MD5運算生成簽名,這裡是第一次簽名,用於呼叫統一下單介面
            String mysign = PayUtil.sign(prestr,WxPayConfig.key,“utf-8”)。toUpperCase();
            logger.info(“=======================第一次簽名:”+ mysign +“============ ======“);
            
            //拼接統一下單介面使用的XML資料,要將上一步生成的簽名一起拼接進去
            String xml =“<xml>”+“<appid>”+ WxPayConfig.appid +“</ appid>”
                    +“<body> <![CDATA [”+ body +“]]> </ body>”
                    +“<mch_id>”+ WxPayConfig.mch_id +“</ mch_id>”
                    +“<nonce_str>”+ nonce_str +“</ nonce_str>”
                    +“<notify_url>”+ WxPayConfig.notify_url +“</ notify_url>”
                    +“<openid>”+ openid +“</ openid>”
                    +“<out_trade_no>”+ orderNo +“</ out_trade_no>”
                    +“<spbill_create_ip>”+ spbill_create_ip +“</ spbill_create_ip>”
                    +“<total_fee>”+ money +“</ total_fee>”
                    +“<trade_type>”+ WxPayConfig.TRADETYPE +“</ trade_type>”
                    +“<sign>”+ mysign +“</ sign>”
                    +“</ xml>”;

            System.out.println(“除錯模式_統一下單介面請求XML資料:”+ xml);

            //呼叫統一下單介面,並接受返回的結果
            字串結果= PayUtil.httpRequest(WxPayConfig.pay_url,“POST”,xml);

            System.out.println(“除錯模式_統一下單介面返回XML資料:”+結果);

            //將解析結果儲存在HashMap中
            Map map = PayUtil.doXMLParse(result);

            String return_code =(String)map.get(“return_code”); //返回狀態碼

            //返回給移動端需要的引數
            Map <String,Object> response = new HashMap <String,Object>();
            if(return_code ==“SUCCESS”|| return_code.equals(return_code)){
                //業務結果
                String prepay_id =(String)map.get(“prepay_id”); //返回的預付單資訊
                response.put(“nonceStr”,nonce_str);
                response.put(“package”,“prepay_id =”+ prepay_id);
                Long timeStamp = System.currentTimeMillis()/ 1000;
                response.put(“timeStamp”,timeStamp +“”); //這邊要將返回的時間戳轉化成字串,不然小程式端呼叫wx.requestPayment方法會報簽名錯誤

                String stringSignTemp =“appId =”+ WxPayConfig.appid +“&nonceStr =”+ nonce_str +“&package = prepay_id =”+ prepay_id +“&signType =”+ WxPayConfig.SIGNTYPE +“&timeStamp =”+ timeStamp;
                //再次簽名,這個簽名用於小程式端呼叫wx.requesetPayment方法
                String paySign = PayUtil.sign(stringSignTemp,WxPayConfig.key,“utf-8”)。toUpperCase();
                logger.info(“=======================第二次簽名:”+ paySign +“============ ======“);

                response.put(“paySign”,paySign);
                //更新訂單資訊
                //業務邏輯程式碼
            }
            response.put(“appid”,WxPayConfig.appid);

            json.setSuccess(真);
            json.setData(響應);
        } catch(例外e){
            e.printStackTrace();
            json.setSuccess(假);
            json.setMsg( “發起失敗”);
        }
        返回json;
    }

4丶所示,微信WxPayConfig配置

/**
 * @Description:
 * @Date: 2018/7/17
 * @Author: wcf
 */
public class WxPayConfig {
    //小程式appid
    public static final String appid = "";
    //微信支付的商戶id
    public static final String mch_id = "";
    //微信支付的商戶金鑰
    public static final String key = "";
    //支付成功後的伺服器回撥url
    public static final String notify_url = "";
    //簽名方式
    public static final String SIGNTYPE = "MD5";
    //交易型別
    public static final String TRADETYPE = "JSAPI";
    //微信統一下單介面地址
    public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
}

5,下面是IpUtils工具類

/**
 * @Description:
 * @Date: 2018/7/17
 * @Author: wcf
 */
public class IpUtils {
    /**
     * IpUtils工具類方法
     * 獲取真實的ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理後會有多個ip值,第一個ip才是真實ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
}

6,StringUtils工具類等等

/**
 * @Description:
 * @Date: 2018/7/17
 * @Author: wcf
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils{
    /**
     * StringUtils工具類方法
     * 獲取一定長度的隨機字串,範圍0-9,a-z
     * @param length:指定字串長度
     * @return 一定長度的隨機字串
     */
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}

7,微信請求回撥contrller

    /**
     * @Description:微信支付
     * @return
     * @author dzg
     * @throws Exception
     * @throws WeixinException
     * @date 2018年7月17日
     */
    @RequestMapping(value="/wxNotify")
    public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        br.close();
        //sb為微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的報文:" + notityXml);
 
        Map map = PayUtil.doXMLParse(notityXml);
 
        String returnCode = (String) map.get("return_code");
        if("SUCCESS".equals(returnCode)){
            //驗證簽名是否正確
            if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){
                /**此處新增自己的業務邏輯程式碼start**/
 
 
                /**此處新增自己的業務邏輯程式碼end**/
 
                //通知微信伺服器已經支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            }
        }else{
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[報文為空]]></return_msg>" + "</xml> ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回撥資料結束");
 
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }