[聚合文章] wx jssdk c# utils

c# 2016-11-14 5 阅读
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Common.Utils
{
    public static class WxUtils
    {
        public static T DeserializeObject<T>(string xml)
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(xml))
            {
                return (T)serializer.Deserialize(tr);
            }
        }

        public static string GetPayPostXml(IDictionary<string, string> dic)
        {
            //XElement el = new XElement("xml", dic.Select(kv => new XElement(kv.Key, new XCData(kv.Value))));
            XElement el = new XElement("xml");

            foreach (var kv in dic)
            {
                if (Regex.IsMatch(kv.Value, @"^[\w\.]+$"))
                {
                    el.Add(new XElement(kv.Key, kv.Value));
                }
                else
                {
                    el.Add(new XElement(kv.Key, new XCData(kv.Value)));
                }
            }

            return el.ToString();
        }

        /// <summary>
        /// 公众号支付签名算法
        /// http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
        /// </summary>
        /// <returns></returns>
        internal static string GetPaySign(IDictionary<string, string> dic, string secret_key)
        {
            var list = dic.Where(t => !string.IsNullOrEmpty(t.Key) && t.Key != "sign" && t.Key != "key").OrderBy(t => t.Key).Select(t => t.Key + "=" + t.Value);
            string stringSignTemp = string.Join("&", list) + "&key=" + secret_key;
            return GetMD5(stringSignTemp);
        }

        /// <summary>
        /// 微信js签名算法
        /// http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95
        /// </summary>
        /// <param name="jsapi_ticket"></param>
        /// <returns></returns>
        public static string GetJSSign(string jsapi_ticket, string url, out string timestamp, out string nonceStr)
        {
            timestamp = GetUnixTimestamp(DateTime.Now).ToString();
            nonceStr = GetNonceStr();

            var dic = new Dictionary<string, string>();

            dic.Add("jsapi_ticket", jsapi_ticket);
            dic.Add("timestamp", timestamp);
            dic.Add("noncestr", nonceStr);
            dic.Add("url", url);

            return GetJSSign(dic);
        }

        /// <summary>
        /// 获取JSAPI签名
        /// </summary>
        internal static string GetJSSign(IDictionary<string, string> dic)
        {
            string string1 = string.Join("&", dic.OrderBy(t => t.Key).Select(t => t.Key.ToLower() + "=" + t.Value));
            string signature = GetSHA1(string1);
            return signature;
        }

        public static string GetMD5(string query)
        {
            MD5 md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));

            StringBuilder result = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                string hex = bytes[i].ToString("X");
                if (hex.Length == 1)
                {
                    result.Append("0");
                }
                result.Append(hex);
            }
            return result.ToString();
        }

        public static string GetSHA1(string str)
        {
            var buffer = System.Text.Encoding.ASCII.GetBytes(str);
            var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            var result = sha.ComputeHash(buffer);

            var strHex = new System.Text.StringBuilder();

            foreach (byte b in result)
            {
                strHex.AppendFormat("{0:x2}", b);
            }

            return strHex.ToString();
        }

        /// <summary>
        /// 清除字典中值为空的项。
        /// </summary>
        /// <param name="dict">待清除的字典</param>
        /// <returns>清除后的字典</returns>
        public static IDictionary<string, T> CleanupDictionary<T>(IDictionary<string, T> dict)
        {
            IDictionary<string, T> newDict = new Dictionary<string, T>(dict.Count);
            IEnumerator<KeyValuePair<string, T>> dem = dict.GetEnumerator();

            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                T value = dem.Current.Value;
                if (value != null)
                {
                    newDict.Add(name, value);
                }
            }

            return newDict;
        }

        /// <summary>
        /// 获取从1970年1月1日到现在的毫秒总数。
        /// </summary>
        /// <returns>毫秒数</returns>
        public static long GetCurrentTimeMillis(DateTime time)
        {
            return (long)time.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
        }

        /// <summary>
        /// 获取unix时间戳。
        /// </summary>
        /// <returns>unix时间戳</returns>
        public static ulong GetUnixTimestamp(DateTime time)
        {
            return (ulong)time.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
        }

        /// <summary>
        /// 32位随机字符串
        /// </summary>
        /// <returns></returns>
        public static string GetNonceStr()
        {
            return Guid.NewGuid().ToString("N").ToUpper();
        }
    }
}

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。