微信支付签名---利用TreeMap实现对参数ASCII升序排序

ASCII码值是:48~57是十个阿拉伯数字;65~90为26个大学英文字母A-Z;97~122是26个小写英文字母a-z;

参数做ASCII码值从小到大排序(字典序)是可以巧妙的借助TreeMap实现

直接看代码:

package com.ifunpay.portal.service;
import com.ifunpay.util.common.StringUtil;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author: lilong
 * @Data: Created on 2018/5/3
 * @Desc:微信支付接口
 */
public class WXPayInterface{
    /**
     * @Author : lilong
     * @Description :根据签名算法得出签名---参数按照参数名ASCII码从小到大排序(字典序)
     * @Date : 10:16 2018/5/3
     * @Param : params 参数是一个集合的map
     **/
    private String getSign(Map params) {
        String Appkey = "lilong123456";
        Map map = new TreeMap<>();
        map.putAll(params);
        //以key1 = value1&key2 = value2拼接参数
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry s : map.entrySet()) {
            String key = s.getKey();
            String value = s.getValue();
            if (StringUtils.isBlank(value)) {//过滤空值
                continue;
            }
            //拼接
            stringBuilder.append(key).append("=").append(value).append("&");
        }
        //拼接商户秘钥
        stringBuilder.append(Appkey);
        if (!map.isEmpty()) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        //根据微信支付文档要求要进行
        String md5 = StringUtil.getMd5HexByUtf8Encoding(stringBuilder.toString());
        return md5;
    }
/**
 * @Author : lilong
 * @Description :微信支付签约
 * @Date : 10:40 2018/5/3
 **/
public String wxContract() {
    //签名所需要的参数
    String appid = "wxd930ea5d5a258f4f";
    String mch_id = "1200009811";
    String device_info = "1000";
    String body = "test";
    String nonce_str = "ibuaiVcKdpRxkhJA";
    Map signMap = new HashMap<>();
    signMap.put("appid", appid);
    signMap.put("mch_id", mch_id);
    signMap.put("device_info", device_info);
    signMap.put("body", body);
    signMap.put("nonce_str", nonce_str);
    String sign = getSign(signMap);
    //签约所需要的其他参数
    String plan_id = "12535";
    String contract_code = "100000";
    Integer request_serial = 1000;
    String contract_display_account = "微信代扣";
    String notify_url = "https://weixin.qq.com";
    String version = "1.0";
    String timestamp = "1414488825";
    String url = "https://api.mch.weixin.qq.com/papay/entrustweb?appid=" + appid
            + "&contract_code=" + contract_code + "&contract_display_account="
            + contract_display_account + "&mch_id=" + mch_id + "¬ify_url=" +
            notify_url + "&plan_id=" + plan_id + "&request_serial=" + request_serial
            + "×tamp=" + timestamp + "&version=" + version + "&sign=" + sign;
    System.err.println("*************" + url + "***********");
    return url;
}

你可能感兴趣的:(java工具类)