微信支付V3 Java jsApi 掃碼支付

LG_227發表於2018-04-04
本文介紹微信掃碼支付,附帶demo:     wisdomdd.cn

111.png

package com.demo;
  
import java.util.SortedMap;
import java.util.TreeMap;
  
import com.utils.GetWxOrderno;
import com.utils.RequestHandler;
import com.utils.Sha1Util;
import com.utils.TenpayUtil;
  
/**
 * @author ex_yangxiaoyi
 * 
 */
public class Demo {
    //微信支付商戶開通後 微信會提供appid和appsecret和商戶號partner
    private static String appid = "";
    private static String appsecret = "";
    private static String partner = "";
    //這個引數partnerkey是在商戶後臺配置的一個32位的key,微信商戶平臺-賬戶設定-安全設定-api安全
    private static String partnerkey = "";
    //openId 是微信使用者針對公眾號的標識,授權的部分這裡不解釋
    private static String openId = "";
    //微信支付成功後通知地址 必須要求80埠並且地址不能帶引數
    private static String notifyurl = "";                                                                    // Key
  
    /**
     * @param args
     */
    public static void main(String[] args) {
          
        //微信支付jsApi
        WxPayDto tpWxPay = new WxPayDto();
        tpWxPay.setOpenId(openId);
        tpWxPay.setBody("商品資訊");
        tpWxPay.setOrderId(getNonceStr());
        tpWxPay.setSpbillCreateIp("127.0.0.1");
        tpWxPay.setTotalFee("0.01");
        getPackage(tpWxPay);
          
        //掃碼支付
        WxPayDto tpWxPay1 = new WxPayDto();
        tpWxPay1.setBody("商品資訊");
        tpWxPay1.setOrderId(getNonceStr());
        tpWxPay1.setSpbillCreateIp("127.0.0.1");
        tpWxPay1.setTotalFee("0.01");
        getCodeurl(tpWxPay1);
    }
      
    /**
     * 獲取微信掃碼支付二維碼連線
     */
    public static String getCodeurl(WxPayDto tpWxPayDto){
          
        // 子商戶號
        String sub_mch_id = tpWxPayDto.getSubMchId();
          
        // 訂單號
        String orderId = tpWxPayDto.getOrderId();
          
        // 附加資料 原樣返回
        String attach = "";
          
        // 總金額以分為單位,不帶小數點
        String totalFee = getMoney(tpWxPayDto.getTotalFee());
          
        // 訂單生成的機器 IP
        String spbill_create_ip = tpWxPayDto.getSpbillCreateIp();
          
        // 這裡notify_url是 支付完成後微信發給該連結資訊,可以判斷會員是否支付成功,改變訂單狀態等。
        String notify_url = notifyurl;
        String trade_type = "NATIVE";
  
        // 商戶號
        String mch_id = partner;
        // 隨機字串
        String nonce_str = getNonceStr();
  
        // 商品描述根據情況修改
        String body = tpWxPayDto.getBody();
  
        // 商戶訂單號
        String out_trade_no = orderId;
  
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", mch_id);
        packageParams.put("sub_mch_id", sub_mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("attach", attach);
        packageParams.put("out_trade_no", out_trade_no);
  
        // 這裡寫的金額為1 分到時修改
        packageParams.put("total_fee", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);
  
        packageParams.put("trade_type", trade_type);
  
        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appid, appsecret, partnerkey);
  
        String sign = reqHandler.createSign(packageParams);
          
        String xml = "<xml>"   "<appid>"   appid   "</appid>"   "<mch_id>"
                  mch_id   "</mch_id>"   "<sub_mch_id>"   sub_mch_id
                  "</sub_mch_id>"   "<nonce_str>"   nonce_str
                  "</nonce_str>"   "<sign>"   sign   "</sign>"
                  "<body><![CDATA["   body   "]]></body>"
                  "<out_trade_no>"   out_trade_no
                  "</out_trade_no>"   "<attach>"   attach   "</attach>"
                  "<total_fee>"   totalFee   "</total_fee>"
                  "<spbill_create_ip>"   spbill_create_ip
                  "</spbill_create_ip>"   "<notify_url>"   notify_url
                  "</notify_url>"   "<trade_type>"   trade_type
                  "</trade_type>"   "</xml>";
        String code_url = "";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
          
        code_url = new GetWxOrderno().getCodeUrl(createOrderURL, xml);
        System.out.println("code_url----------------" code_url);
          
        return code_url;
    }
  
    /**
     * 獲取請求預支付id報文
     * @return
     */
    @SuppressWarnings("static-access")
    public static String getPackage(WxPayDto tpWxPayDto) {
          
        String openId = tpWxPayDto.getOpenId();
        // 子商戶號
        String sub_mch_id = tpWxPayDto.getSubMchId();
        // 訂單號
        String orderId = tpWxPayDto.getOrderId();
        // 附加資料 原樣返回
        String attach = "";
        // 總金額以分為單位,不帶小數點
        String totalFee = getMoney(tpWxPayDto.getTotalFee());
          
        // 訂單生成的機器 IP
        String spbill_create_ip = tpWxPayDto.getSpbillCreateIp();
        // 這裡notify_url是 支付完成後微信發給該連結資訊,可以判斷會員是否支付成功,改變訂單狀態等。
        String notify_url = notifyurl;
        String trade_type = "JSAPI";
  
        // ---必須引數
        // 商戶號
        String mch_id = partner;
        // 隨機字串
        String nonce_str = getNonceStr();
  
        // 商品描述根據情況修改
        String body = tpWxPayDto.getBody();
  
        // 商戶訂單號
        String out_trade_no = orderId;
  
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", mch_id);
        packageParams.put("sub_mch_id", sub_mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("attach", attach);
        packageParams.put("out_trade_no", out_trade_no);
  
        // 這裡寫的金額為1 分到時修改
        packageParams.put("total_fee", totalFee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);
  
        packageParams.put("trade_type", trade_type);
        packageParams.put("openid", openId);
  
        RequestHandler reqHandler = new RequestHandler(null, null);
        reqHandler.init(appid, appsecret, partnerkey);
  
        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>"   "<appid>"   appid   "</appid>"   "<mch_id>"
                  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>"   "<attach>"   attach   "</attach>"
                  "<total_fee>"   totalFee   "</total_fee>"
                  "<spbill_create_ip>"   spbill_create_ip
                  "</spbill_create_ip>"   "<notify_url>"   notify_url
                  "</notify_url>"   "<trade_type>"   trade_type
                  "</trade_type>"   "<openid>"   openId   "</openid>"
                  "</xml>";
        String prepay_id = "";
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
          
          
        prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
  
        System.out.println("獲取到的預支付ID:"   prepay_id);
          
          
        //獲取prepay_id後,拼接最後請求支付所需要的package
          
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        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);
          
        String finaPackage = "\"appId\":\""   appid   "\",\"timeStamp\":\""   timestamp
          "\",\"nonceStr\":\""   nonce_str   "\",\"package\":\""
          packages   "\",\"signType\" : \"MD5"   "\",\"paySign\":\""
          finalsign   "\"";
  
        System.out.println("V3 jsApi package:" finaPackage);
        return finaPackage;
    }
  
    /**
     * 獲取隨機字串
     * @return
     */
    public static String getNonceStr() {
        // 隨機數
        String currTime = TenpayUtil.getCurrTime();
        // 8位日期
        String strTime = currTime.substring(8, currTime.length());
        // 四位隨機數
        String strRandom = TenpayUtil.buildRandom(4)   "";
        // 10位序列號,可以自行調整。
        return strTime   strRandom;
    }
  
    /**
     * 元轉換成分
     * @param money
     * @return
     */
    public static String getMoney(String amount) {
        if(amount==null){
            return "";
        }
        // 金額轉化為分為單位
        String currency =  amount.replaceAll("\\$|\\¥|\\,", "");  //處理包含, ¥ 或者$的金額  
        int index = currency.indexOf(".");  
        int length = currency.length();  
        Long amLong = 0l;  
        if(index == -1){  
            amLong = Long.valueOf(currency "00");  
        }else if(length - index >= 3){  
            amLong = Long.valueOf((currency.substring(0, index 3)).replace(".", ""));  
        }else if(length - index == 2){  
            amLong = Long.valueOf((currency.substring(0, index 2)).replace(".", "") 0);  
        }else{  
            amLong = Long.valueOf((currency.substring(0, index 1)).replace(".", "") "00");  
        }  
        return amLong.toString(); 
    }
}

相關文章