SpringBoot实现小程序微信支付统一下单

SpringBoot实现微信支付统一下单


最近做小程序有需要用到微信支付,而在页面拉起微信支付前需要先进行统一下单,然后再返回参数给前端调用微信支付wx.requestPayment。网上参考了很多代码,写得都比较繁杂,所以自己写了一个比较容易理解的。下面贴上关键代码:

@Service
public class WxPayServiceImpl  implements WxPayService{
    @Override
    public Map<String, String> xcxPayment(String orderNo, BigDecimal money, int userid) {

        /* 准备统一下单参数 */
        String appid = "小程序的appID";
        String mch_id = "商户id";
        String body = "商品名称";
        String secretKey = "32位商户密匙";
        String nonce_str = getram();//获取随机字符串
        String out_trade_no = orderNo;//唯一订单号,根据自己业务编写
        BigDecimal bignum2 = new BigDecimal("100");//下单金额转换为分单位
        money = money.multiply(bignum2);
        int total_fee = money.intValue();
       
        String trade_type = "JSAPI";//小程序默认为JSAPI
        String notify_url = "www.baidu.com";//接收返回数据的url,可以另写一个接口也可以随便写

        KUser user = userMapper.selectByPrimaryKey(userid);//获取下单用户的openid
        String openid = "";
        if(user!=null){
            openid = user.getOpenId();
        }

        //把参数放在map中,准备进行签名加密
        Map<String, String> maps = new HashMap<>();
        maps.put("openid", openid);
        maps.put("appid", appid);
        maps.put("mch_id", mch_id);
        maps.put("nonce_str", nonce_str);
        maps.put("body", body);
        maps.put("out_trade_no", out_trade_no);
        maps.put("total_fee", String.valueOf(total_fee));
        maps.put("trade_type", trade_type);
        maps.put("notify_url", notify_url);
        String spbill_create_ip = null;
        String sign = null;
        try {
            spbill_create_ip = getIp(); //获取本地IP
            maps.put("spbill_create_ip", spbill_create_ip);
           
            sign = qianming(secretKey, maps);//进行签名加密
            System.out.println(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //拼接需要发送参数
        String x = "<xml>" + "<appid>" + appid + "</appid>" + "<body>" + body
                + "</body>" + "<mch_id>" + mch_id + "</mch_id>" + "<nonce_str>"
                + nonce_str + "</nonce_str>" + "<notify_url>" + notify_url
                + "</notify_url>" + "<out_trade_no>" + out_trade_no
                + "</out_trade_no>" + "<spbill_create_ip>" + spbill_create_ip
                + "</spbill_create_ip>" + "<total_fee>" + total_fee
                + "</total_fee>" + "<trade_type>" + trade_type
                + "</trade_type>" + "<sign>" + sign + "</sign>" + "<openid>"
                + openid + "</openid>" + "</xml>";


        /* api地址 */
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        Map<String, String> resultmaps = new HashMap<>();
        String result =null;
        try {
            x = new String(x.getBytes("UTF-8"), "ISO-8859-1");//发送统下单请求
            result = fasong(x, url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultmaps = xmlStrToMap(result);//返回结果是xml字符串,转换成Map

        //将统一下单返回的参数进行二次签名加密
        if(resultmaps.get("result_code").equals("SUCCESS")&&resultmaps.get("return_code").equals("SUCCESS")){
            //准备二次签名加密的参数
            String nonceStr = getram();
            String package1 = "prepay_id=" + resultmaps.get("prepay_id");
            String timeStamp = (new Date().getTime() / 1000) + "";
            Map<String, String> twoMap = new HashMap<>();
            twoMap.put("appId", appid);
            twoMap.put("package", package1);
            twoMap.put("timeStamp", timeStamp);
            twoMap.put("nonceStr", nonceStr);
            twoMap.put("signType", "MD5");

            String paySign = "";
            try {
                paySign = qianming(secretKey, twoMap);//进行二次签名
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            //已准备好wx.requestPayment所需要的参数,返回参数给前端拉起支付!
            Map<String, String> overMap = new HashMap<>();
            overMap.put("timeStamp", timeStamp);
            overMap.put("nonceStr", nonceStr);
            overMap.put("package", package1);
            overMap.put("signType", "MD5");
            overMap.put("paySign", paySign);

            return overMap;
        }else {
            return null;
        }


    }

    /* 发送统一下单请求 */
    public String fasong(String xmlInfo, String URL) throws Exception {
        java.net.URL postUrl = new URL(URL);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.connect();
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());
        // String content = URLEncoder.encode("字符串值", "编码");
        out.writeBytes(xmlInfo);
        out.flush();
        out.close();
        // 获取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        String resultlin = "";
        while ((line = reader.readLine()) != null) {
            resultlin = resultlin + line;
        }
        reader.close();
        // 该干的都干完了,记得把连接断了
        connection.disconnect();
        return resultlin;

    }

    /* String转为Map */
    public Map<String, String> xmlStrToMap(String xmlStr) {
        System.out.println(xmlStr);
        Map<String, String> map = new HashMap<String, String>();
        Document doc;
        try {
            doc = DocumentHelper.parseText(xmlStr);
            Element root = doc.getRootElement();
            List children = root.elements();
            if (children != null && children.size() > 0) {
                for (int i = 0; i < children.size(); i++) {
                    Element child = (Element) children.get(i);
                    map.put(child.getName(), child.getTextTrim());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /* 随机生成32位字符 */
    public String getram() {
        int maxNum = 58;
        int i;
        int count = 0;
        char[] str = { 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P',
                'O', 'N', 'M', 'L', 'K', 'J', 'I', 'H', 'G', 'F', 'E', 'D',
                'C', 'B', 'A', 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r',
                'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f',
                'e', 'd', 'c', 'b', 'a', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', '0' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < 32) {
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        System.out.println(pwd.toString());
        return pwd.toString();
    }

    /* 签名加密 */
    public String qianming(String secretKey, Map<String, String> maps)
            throws UnsupportedEncodingException {
        // 1. 参数名按照ASCII码表升序排序
        String[] keys = maps.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        // 2. 按照排序拼接参数名与参数值
        StringBuffer paramBuffer = new StringBuffer();
        for (String key : keys) {
            paramBuffer.append("&" + key).append(
                    maps.get(key) == null ? "" : "=" + maps.get(key));
        }
        // 3. 将secretKey拼接到最后
         paramBuffer = paramBuffer.append("&key=" + secretKey);
        System.out.println(paramBuffer);
        String pa = paramBuffer.substring(1);
        // 4. MD5是128位长度的摘要算法,用16进制表示,一个十六进制的字符能表示4个位,所以签名后的字符串长度固定为32个十六进制字符。
       //return DigestUtils.md5Hex(pa.getBytes("UTF-8")).toUpperCase();
        return DigestUtils.md5DigestAsHex(pa.getBytes("UTF-8")).toUpperCase();
    }

    /* 获取IP地址 */
    public String getIp() throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        return addr.getHostAddress();
    }
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值