漂泊雪狼的博客

思考,讨论,分享C#,JavaScript,.NET,Oracle,SQL Server……技术

导航

微信红包签名算法 C#代码实现

Posted on 2015-10-21 16:30  漂泊雪狼  阅读(2038)  评论(0编辑  收藏  举报
string stringA = "appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA";

            string stringSignTemp = stringA + "&key=192006250b4c09247ec02edce69f6a2d";

            string sign = MD5Helper.GetMD5Hash(stringSignTemp).ToUpper();
 public class MD5Helper
    {
        public static string GetMD5Hash(string value)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hashByte = md5.ComputeHash(Encoding.Default.GetBytes(value));
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hashByte)
            {
                sb.Append(b.ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
    }

 

假设传送的参数如下:

appid: wxd930ea5d5a258f4f

mch_id: 10000100

device_info: 1000

body: test

nonce_str: ibuaiVcKdpRxkhJA

第一步:对参数按照key=value的格式,并按照参数名ASCII字典序排序如下:

stringA="appid=wxd930ea5d5a258f4f&body=test&device_info=1000&mch_id=10000100&nonce_str=ibuaiVcKdpRxkhJA";

第二步:拼接API密钥:

stringSignTemp="stringA&key=192006250b4c09247ec02edce69f6a2d"

sign=MD5(stringSignTemp).toUpperCase()="9A0A8659F005D6984697E2CA0A9CF3B7"

最终得到最终发送的数据:

<xml>

<appid>wxd930ea5d5a258f4f</appid>

<mch_id>10000100</mch_id>

<device_info>1000<device_info>

<body>test</body>

<nonce_str>ibuaiVcKdpRxkhJA</nonce_str>

<sign>9A0A8659F005D6984697E2CA0A9CF3B7</sign>

<xml>

https://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=4_3