微信支付-签名生成工具-Java

1、微信接口文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3

2、具体代码

package com.lyn.v5.polish.infrastructure.utils;

import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class WeixinPayUtils {

    /**
     * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
     *
     * @param parameters
     * @param key
     * @return
     */
    public static String createSign(SortedMap<String, String> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sbkey = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (StringUtils.isNotBlank(v.toString())) {
                sb.append(k + "=" + v + "&");
                sbkey.append(k + "=" + v + "&");
            }
        }
        sbkey = sbkey.append("key=" + key);
        return MD5Util.textToMD5U32(sbkey.toString()).toUpperCase();
    }

    public static void main(String[] args) throws Exception {
        String key = "192006250b4c09247ec02edce69f6a2d";
        String s = WXPayUtil.generateSignedXml(initRequestMapTest(key), key);
        System.out.println(s);
    }

    /**
     * 此测试方法所用举例数据,与官方文档中的数据同
     * @param key
     * @return
     */
    private static SortedMap<String, String> initRequestMapTest(String key) {
        SortedMap<String, String> requestMap = new TreeMap();
        requestMap.put("appid", "wxd930ea5d5a258f4f");
        requestMap.put("mch_id", "10000100");
        requestMap.put("device_info", "1000");
        requestMap.put("body", "test");
        requestMap.put("nonce_str", "ibuaiVcKdpRxkhJA");//随机串生成  WXPayUtil.generateNonceStr()
        requestMap.put("sign", createSign(requestMap, key));
        return requestMap;
    }

}

3、执行结果

以下粘贴了微信接口文档中的示例,可见,二者生成的最终请求串是相同的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值