.net 小程序获取用户UnionID
.net 小程序获取用户UnionID
第一次写博客,写的不好多多海涵!
1.小程序获取UnionID的流程
用code去换取session_key,然后去解密小程序获取到的那串字符!
话不多说,原理大家都懂!!!!!!
直接上代码
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/ (晨风电影)