微信小程序后台获取用户手机,openid(C#)
- 官网地址
- 注意事项
- 前端调用 wx.login 保存返回的code
- 前端调用 wx.getUserInfo 保存返回的encryptedData 与 iv
- 前端组合 code,encryptedData,iv传入后台进行解密
- 官网上写的是对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。但是设置的时候,千万不要设置128位。会出现乱码。
- 出现Padding is invalid and cannot be removed。你的sessionKey有问题。千万别百度网上乱起八糟的解决办法。查询第一个步骤。
```flow
st=>start: 前端传入参数code,encryptedData,iv
op=>operation: 根据自己的配置调用获取session_key与openid接口(注意请求时效)
op1=>operation: 返回的json字符串获取sessionKey,openid
op2=>operation: 解密encryptedData
op3=>operation: 处理待解密字符串格式
op4=>operation: 创建方法进行解密
e=>end: 结束
st->op->op1->op2->op3->op4->e
```
/// sessionKey 是用户登陆code
/// text 加密内容
/// iv 加密配置
public IActionResult DecryptWXString(string sessionKey, string text, string iv)
{
string openid = "";
string url = @"https://api.weixin.qq.com/sns/jscode2session?appid=填写自己的&secret=填写自己的&js_code="+ sessionKey + "&grant_type=authorization_code";
// 简单的http 请求自己写
string str = HttpRequestHelp.RequestUrl.GetUrlAsync(url).Result;
JObject json1 = (JObject)JsonConvert.DeserializeObject(str);
if (json1["session_key"] == null || json1["openid"] == null)
{
ro.code = "3";
ro.msg = "获取session_key失败!";
}
else
{
sessionKey = json1["session_key"].ToString();
openid = json1["openid"].ToString();
}
if (!string.IsNullOrEmpty(sessionKey) && !string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(iv))
{
// 传输的数据有变化,必须处理,不然FromBase64String 报错
text = text.Replace("%", "").Replace(",", "").Replace(" ", "+");
sessionKey = sessionKey.Replace("%", "").Replace(",", "").Replace(" ", "+");
iv = iv.Replace("%", "").Replace(",", "").Replace(" ", "+");
string result = "";
using (Aes aesAlg = Aes.Create())
{
try
{
aesAlg.Key = Convert.FromBase64String(sessionKey);
aesAlg.IV = Convert.FromBase64String(iv);
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
//aesAlg.BlockSize = 128; //这里记得千万不安装官网的说明加上,不然解析出乱码
ICryptoTransform decryptor = aesAlg.CreateDecryptor();
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(text)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
JObject json3 = (JObject)JsonConvert.DeserializeObject(result);
if (json3["purePhoneNumber"] != null)
{
ro.code = "0";
ro.data = new
{
phone = json3["purePhoneNumber"].ToString(),
openid = openid
};
return Json(ro);
}
}
}
}
}
catch(Exception ex)
{
ro.code = "4";
ro.msg = "系统异常!";
if (aesAlg != null)
aesAlg.Clear();
}
finally
{
if (aesAlg != null)
aesAlg.Clear();
}
}
}
return Json(ro);
}