第一次写博客,写的不好多多海涵!
小程序获取UnionID的流程,用code去换取session_key,然后去解密小程序获取到的那串字符,目前小程序还没提供.net 解密案例,在这里贴出来,互相学习一下!
这里就不多说了,获取原理大家都懂得!
直接上代码
备注:以下代码只供参考,不考虑代码稳健性!!!!!!
public string GetMiniAppUserUnionID(string code, string userInfo, string iv)
{
Dictionary<string, string> parames = new Dictionary<string, string>();
parames.Add("appid", "");
parames.Add("secret", "");
parames.Add("js_code", code);
parames.Add("grant_type", "authorization_code");
string res = HttpWebResponseHelper.Get("https://api.weixin.qq.com/sns/jscode2session", parames);
var obj = Parse(res);
string unionid="";
if (!res.Contains("errcode"))
{
userJson = AESDecrypt(userInfo, obj.session_key, iv);
var userobj = Parse(userJson);
unionid = userobj.unionId;
}
return unionid ;
}
AESDecrypt解密算法
/// <summary>
/// AES解密
/// </summary>
/// <param name="text"></param>
/// <param name="password"></param>
/// <param name="iv"></param>
/// <returns></returns>
public static string AESDecrypt(string text, string password, string iv)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7; byte[] encryptedData = Convert.FromBase64String(text);
byte[] pwdBytes = Convert.FromBase64String(password); rijndaelCipher.Key = pwdBytes; if (!string.IsNullOrEmpty(iv))
{
byte[] ivBytes = Convert.FromBase64String(iv);
rijndaelCipher.IV = ivBytes;
}
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, , encryptedData.Length); return Encoding.UTF8.GetString(plainText); }
序列化方法
public static dynamic Parse(string json, Encoding encoding)
{
using (var reader = JsonReaderWriterFactory.CreateJsonReader(encoding.GetBytes(json), XmlDictionaryReaderQuotas.Max))
{
return ToValue(XElement.Load(reader));
}
}
打个广告: 晨风电影 https://www.chenfengdy.top/