C#微信小程序服务端获取用户解密信息实例代码
C#微信小程序服务端获取用户解密信息实例代码
实现代码:
usingAIOWeb.Models;
usingNewtonsoft.Json;
usingNewtonsoft.Json.Linq;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Linq;
usingSystem.Web;
namespaceAIOWeb
{
///
///wxapi的摘要说明
///
publicclasswxapi:IHttpHandler
{
publicvoidProcessRequest(HttpContextcontext)
{
context.Response.ContentType="text/plain";
stringcode="";
stringiv="";
stringencryptedData="";
try
{
code=HttpContext.Current.Request.QueryString["code"].ToString();
iv=HttpContext.Current.Request.QueryString["iv"].ToString();
encryptedData=HttpContext.Current.Request.QueryString["encryptedData"].ToString();
}
catch(Exceptionex)
{
context.Response.Write(ex.ToString());
}
stringAppid="wxdb2641f85b04f1b3";
stringSecret="8591d8cd7197b9197e17b3275329a1e7";
stringgrant_type="authorization_code";
//向微信服务端使用登录凭证code获取session_key和openid
stringurl="https://api.weixin.qq.com/sns/jscode2session?appid="+Appid+"&secret="+Secret+"&js_code="+code+"&grant_type="+grant_type;
stringtype="utf-8";
AIOWeb.Models.GetUsersHelperGetUsersHelper=newAIOWeb.Models.GetUsersHelper();
stringj=GetUsersHelper.GetUrltoHtml(url,type);//获取微信服务器返回字符串
//将字符串转换为json格式
JObjectjo=(JObject)JsonConvert.DeserializeObject(j);
resultres=newresult();
try
{
//微信服务器验证成功
res.openid=jo["openid"].ToString();
res.session_key=jo["session_key"].ToString();
}
catch(Exception)
{
//微信服务器验证失败
res.errcode=jo["errcode"].ToString();
res.errmsg=jo["errmsg"].ToString();
}
if(!string.IsNullOrEmpty(res.openid))
{
//用户数据解密
GetUsersHelper.AesIV=iv;
GetUsersHelper.AesKey=res.session_key;
stringresult=GetUsersHelper.AESDecrypt(encryptedData);
//存储用户数据
JObject_usrInfo=(JObject)JsonConvert.DeserializeObject(result);
userInfouserInfo=newuserInfo();
userInfo.openId=_usrInfo["openId"].ToString();
try//部分验证返回值中没有unionId
{
userInfo.unionId=_usrInfo["unionId"].ToString();
}
catch(Exception)
{
userInfo.unionId="unionId";
}
userInfo.nickName=_usrInfo["nickName"].ToString();
userInfo.gender=_usrInfo["gender"].ToString();
userInfo.city=_usrInfo["city"].ToString();
userInfo.province=_usrInfo["province"].ToString();
userInfo.country=_usrInfo["country"].ToString();
userInfo.avatarUrl=_usrInfo["avatarUrl"].ToString();
objectwatermark=_usrInfo["watermark"].ToString();
objectappid=_usrInfo["watermark"]["appid"].ToString();
objecttimestamp=_usrInfo["watermark"]["timestamp"].ToString();
#region
//创建连接池对象(与数据库服务器进行连接)
SqlConnectionconn=newSqlConnection("server=127.0.0.1;database=Test;uid=sa;pwd=1");
//打开连接池
conn.Open();
//创建命令对象
stringQrystr="SELECT*FROMWeChatUsersWHEREopenId='"+userInfo.openId+"'";
SqlCommandcmdQry=newSqlCommand(Qrystr,conn);
objectobj=cmdQry.ExecuteScalar();
if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value)))
{
stringstr="INSERTINTOWeChatUsers([UnionId],[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],[Timestamp],[Memo],[counts])VALUES('"+userInfo.unionId+"','"+userInfo.openId+"','"+userInfo.nickName+"','"+userInfo.gender+"','"+userInfo.city+"','"+userInfo.province+"','"+userInfo.country+"','"+userInfo.avatarUrl+"','"+appid.ToString()+"','"+timestamp.ToString()+"','来自微信小程序','1')";
SqlCommandcmdUp=newSqlCommand(str,conn);
//执行操作
try
{
introw=cmdUp.ExecuteNonQuery();
}
catch(Exceptionex)
{
context.Response.Write(ex.ToString());
}
}
else
{
//多次访问,记录访问次数counts更新unionId是预防最初没有,后期关联后却仍未记录
stringstr="UPDATEdbo.WeChatUsersSETcounts=counts+1,UnionId='"+userInfo.unionId+"'WHEREOpenId='"+userInfo.openId+"'";
SqlCommandcmdUp=newSqlCommand(str,conn);
introw=cmdUp.ExecuteNonQuery();
}
//关闭连接池
conn.Close();
#endregion
//返回解密后的用户数据
context.Response.Write(result);
}
else
{
context.Response.Write(j);
}
}
publicboolIsReusable
{
get
{
returnfalse;
}
}
}
}
GetUsersHelper帮助类
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Linq;
usingSystem.Security.Cryptography;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceAIOWeb.Models
{
publicclassGetUsersHelper
{
///
///获取链接返回数据
///
///链接
///请求类型
///
publicstringGetUrltoHtml(stringUrl,stringtype)
{
try
{
System.Net.WebRequestwReq=System.Net.WebRequest.Create(Url);
//Gettheresponseinstance.
System.Net.WebResponsewResp=wReq.GetResponse();
System.IO.StreamrespStream=wResp.GetResponseStream();
//DimreaderAsStreamReader=NewStreamReader(respStream)
using(System.IO.StreamReaderreader=newSystem.IO.StreamReader(respStream,Encoding.GetEncoding(type)))
{
returnreader.ReadToEnd();
}
}
catch(System.Exceptionex)
{
returnex.Message;
}
}
#region微信小程序用户数据解密
publicstaticstringAesKey;
publicstaticstringAesIV;
///
///AES解密
///
///输入的数据encryptedData
///key
///向量128
///解密后的字符串
publicstringAESDecrypt(stringinputdata)
{
try
{
AesIV=AesIV.Replace("","+");
AesKey=AesKey.Replace("","+");
inputdata=inputdata.Replace("","+");
byte[]encryptedData=Convert.FromBase64String(inputdata);
RijndaelManagedrijndaelCipher=newRijndaelManaged();
rijndaelCipher.Key=Convert.FromBase64String(AesKey);//Encoding.UTF8.GetBytes(AesKey);
rijndaelCipher.IV=Convert.FromBase64String(AesIV);//Encoding.UTF8.GetBytes(AesIV);
rijndaelCipher.Mode=CipherMode.CBC;
rijndaelCipher.Padding=PaddingMode.PKCS7;
ICryptoTransformtransform=rijndaelCipher.CreateDecryptor();
byte[]plainText=transform.TransformFinalBlock(encryptedData,0,encryptedData.Length);
stringresult=Encoding.UTF8.GetString(plainText);
returnresult;
}
catch(Exception)
{
returnnull;
}
}
#endregion
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!