C#微信小程序服务端获取用户解密信息实例代码
程序员文章站
2023-12-03 08:11:22
c#微信小程序服务端获取用户解密信息实例代码
实现代码:
using aioweb.models;
using newtonsoft.json;...
c#微信小程序服务端获取用户解密信息实例代码
实现代码:
using aioweb.models; using newtonsoft.json; using newtonsoft.json.linq; using system; using system.collections.generic; using system.data; using system.data.sqlclient; using system.linq; using system.web; namespace aioweb { /// <summary> /// wxapi 的摘要说明 /// </summary> public class wxapi : ihttphandler { public void processrequest(httpcontext context) { context.response.contenttype = "text/plain"; string code = ""; string iv = ""; string encrypteddata = ""; try { code = httpcontext.current.request.querystring["code"].tostring(); iv = httpcontext.current.request.querystring["iv"].tostring(); encrypteddata = httpcontext.current.request.querystring["encrypteddata"].tostring(); } catch (exception ex) { context.response.write(ex.tostring()); } string appid = "wxdb2641f85b04f1b3"; string secret = "8591d8cd7197b9197e17b3275329a1e7"; string grant_type = "authorization_code"; //向微信服务端 使用登录凭证 code 获取 session_key 和 openid string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=" + grant_type; string type = "utf-8"; aioweb.models.getusershelper getusershelper = new aioweb.models.getusershelper(); string j = getusershelper.geturltohtml(url, type);//获取微信服务器返回字符串 //将字符串转换为json格式 jobject jo = (jobject)jsonconvert.deserializeobject(j); result res = new result(); 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; string result = getusershelper.aesdecrypt(encrypteddata); //存储用户数据 jobject _usrinfo = (jobject)jsonconvert.deserializeobject(result); userinfo userinfo = new userinfo(); 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(); object watermark = _usrinfo["watermark"].tostring(); object appid = _usrinfo["watermark"]["appid"].tostring(); object timestamp = _usrinfo["watermark"]["timestamp"].tostring(); #region //创建连接池对象(与数据库服务器进行连接) sqlconnection conn = new sqlconnection("server=127.0.0.1;database=test;uid=sa;pwd=1"); //打开连接池 conn.open(); //创建命令对象 string qrystr = "select * from wechatusers where openid='" + userinfo.openid + "'"; sqlcommand cmdqry = new sqlcommand(qrystr, conn); object obj = cmdqry.executescalar(); if ((object.equals(obj, null)) || (object.equals(obj, system.dbnull.value))) { string str = "insert into wechatusers ([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')"; sqlcommand cmdup = new sqlcommand(str, conn); // 执行操作 try { int row = cmdup.executenonquery(); } catch (exception ex) { context.response.write(ex.tostring()); } } else { //多次访问,记录访问次数counts 更新unionid是预防最初没有,后期关联后却仍未记录 string str = "update dbo.wechatusers set counts = counts+1,unionid = '" + userinfo.unionid + "' where openid='" + userinfo.openid + "'"; sqlcommand cmdup = new sqlcommand(str, conn); int row = cmdup.executenonquery(); } //关闭连接池 conn.close(); #endregion //返回解密后的用户数据 context.response.write(result); } else { context.response.write(j); } } public bool isreusable { get { return false; } } } }
getusershelper 帮助类
using system; using system.collections.generic; using system.io; using system.linq; using system.security.cryptography; using system.text; using system.threading.tasks; namespace aioweb.models { public class getusershelper { /// <summary> /// 获取链接返回数据 /// </summary> /// <param name="url">链接</param> /// <param name="type">请求类型</param> /// <returns></returns> public string geturltohtml(string url, string type) { try { system.net.webrequest wreq = system.net.webrequest.create(url); // get the response instance. system.net.webresponse wresp = wreq.getresponse(); system.io.stream respstream = wresp.getresponsestream(); // dim reader as streamreader = new streamreader(respstream) using (system.io.streamreader reader = new system.io.streamreader(respstream, encoding.getencoding(type))) { return reader.readtoend(); } } catch (system.exception ex) { return ex.message; } } #region 微信小程序用户数据解密 public static string aeskey; public static string aesiv; /// <summary> /// aes解密 /// </summary> /// <param name="inputdata">输入的数据encrypteddata</param> /// <param name="aeskey">key</param> /// <param name="aesiv">向量128</param> /// <returns name="result">解密后的字符串</returns> public string aesdecrypt(string inputdata) { try { aesiv = aesiv.replace(" ", "+"); aeskey = aeskey.replace(" ", "+"); inputdata = inputdata.replace(" ", "+"); byte[] encrypteddata = convert.frombase64string(inputdata); rijndaelmanaged rijndaelcipher = new rijndaelmanaged(); 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; icryptotransform transform = rijndaelcipher.createdecryptor(); byte[] plaintext = transform.transformfinalblock(encrypteddata, 0, encrypteddata.length); string result = encoding.utf8.getstring(plaintext); return result; } catch (exception) { return null; } } #endregion } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
上一篇: 常用的js方法合集