第一次寫博客,寫的不好多多海涵! 小程式獲取UnionID的流程,用code去換取session_key,然後去解密小程式獲取到的那串字元,目前小程式還沒提供.net 解密案例,在這裡貼出來,互相學習一下! 這裡就不多說了,獲取原理大家都懂得! 直接上代碼 備註:以下代碼只供參考,不考慮代碼穩健性! ...
第一次寫博客,寫的不好多多海涵!
小程式獲取UnionID的流程,用code去換取session_key,然後去解密小程式獲取到的那串字元,目前小程式還沒提供.net 解密案例,在這裡貼出來,互相學習一下!
這裡就不多說了,獲取原理大家都懂得!
直接上代碼
備註:以下代碼只供參考,不考慮代碼穩健性!!!!!!
1 public string GetMiniAppUserUnionID(string code, string userInfo, string iv) 2 { 5 Dictionary<string, string> parames = new Dictionary<string, string>(); 6 parames.Add("appid", ""); 7 parames.Add("secret", ""); 8 parames.Add("js_code", code); 9 parames.Add("grant_type", "authorization_code"); 10 string res = HttpWebResponseHelper.Get("https://api.weixin.qq.com/sns/jscode2session", parames); 12 var obj = Parse(res);
string unionid=""; 13 if (!res.Contains("errcode")) 14 { 15 userJson = AESDecrypt(userInfo, obj.session_key, iv); 16 var userobj = Parse(userJson); 17 unionid = userobj.unionId;
}
return unionid ;
19 }
AESDecrypt解密演算法
1 /// <summary> 2 /// AES解密 3 /// </summary> 4 /// <param name="text"></param> 5 /// <param name="password"></param> 6 /// <param name="iv"></param> 7 /// <returns></returns> 8 public static string AESDecrypt(string text, string password, string iv) 9 { 10 RijndaelManaged rijndaelCipher = new RijndaelManaged(); 11 rijndaelCipher.Mode = CipherMode.CBC; 12 rijndaelCipher.Padding = PaddingMode.PKCS7; 13 14 byte[] encryptedData = Convert.FromBase64String(text); 15 byte[] pwdBytes = Convert.FromBase64String(password); 16 17 rijndaelCipher.Key = pwdBytes; 18 19 if (!string.IsNullOrEmpty(iv)) 20 { 21 byte[] ivBytes = Convert.FromBase64String(iv); 22 rijndaelCipher.IV = ivBytes; 23 } 24 ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); 25 byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); 26 27 return Encoding.UTF8.GetString(plainText); 28 29 }
序列化方法
1 public static dynamic Parse(string json, Encoding encoding) 2 { 3 using (var reader = JsonReaderWriterFactory.CreateJsonReader(encoding.GetBytes(json), XmlDictionaryReaderQuotas.Max)) 4 { 5 return ToValue(XElement.Load(reader)); 6 } 7 }
打個廣告: 晨風電影 https://www.chenfengdy.top/