1、appid非个人类型
2、解码需要的session_key、IV、encryptedData,session_key可以先用上篇文章的方法获取,以参数传递;或者传递code,在服务器上当场获取。
当场获取的完整代码是:保存成ashx文件,上传到服务器。
<% @ webhandler language="C#" class="AverageHandler" %>
using System;
using System.Net;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using LitJson;
public class AverageHandler : IHttpHandler
{
public bool IsReusable
{ get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.ContentType = "application/json";
HttpRequest Request = ctx.Request;
string text = Request["encryptedData"];
string IV = Request["iv"];
//小程序appid和appsecret配置
string appid = "XXXXXXXXXXXXXXX";
string secret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
string code = Request["code"];//微信获取登录的口令
Stream s_re = WebRequest.Create("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code").GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s_re, Encoding.UTF8);
string strLine = sr.ReadToEnd();
sr.Close();
try
{
JsonData jo = JsonMapper.ToObject(strLine);
string Key = jo["session_key"].ToString();
string weixinID = jo["openid"].ToString();
string str= AES_decrypt(text,Key,IV);
ctx.Response.Write(str);
}
catch (Exception ex)
{
//return "";
}
}
public string AES_decrypt(string encryptedDataStr, string key, string iv)
{
RijndaelManaged rijalg = new RijndaelManaged();
//-----------------
//设置 cipher 格式 AES-128-CBC
rijalg.KeySize = 128;
rijalg.Padding = PaddingMode.PKCS7;
rijalg.Mode = CipherMode.CBC;
rijalg.Key = Convert.FromBase64String(key);
rijalg.IV = Convert.FromBase64String(iv);
byte[] encryptedData= Convert.FromBase64String(encryptedDataStr);
//解密
ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);
string result;
using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}
}
}
return result;
}
}
小程序端:wxml
小程序端:js
getPhoneNumber: function (e) {
var that = this;
wx.login({
success: res => {
console.log(res.code, e.detail.iv, e.detail.encryptedData)
wx.request({
//后台接口地址
url: 'https://www.XXXXXXX.com/weixin/getphone.ashx',
data: {
code: res.code,
iv: e.detail.iv,
encryptedData: e.detail.encryptedData,
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log(res.data)
}
})
}
})
}
结果: