C#微信小程序服务端获取用户解密信息实例代码


Posted in Javascript onMarch 10, 2017

 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 
  } 
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Javascript 相关文章推荐
JS学习之一个简易的日历控件
Mar 24 Javascript
浅谈Javascript数组索引
Jul 29 Javascript
jQuery获取cookie值及删除cookie用法实例
Apr 15 Javascript
Angular表单验证实例详解
Oct 20 Javascript
浅谈Vue的基本应用
Dec 27 Javascript
jquery 禁止鼠标右键并监听右键事件
Apr 27 jQuery
vuex学习之Actions的用法详解
Aug 29 Javascript
javaScript实现滚动条事件详解
Mar 24 Javascript
React组件中的this的具体使用
Feb 28 Javascript
vue实现局部刷新的实现示例
Apr 16 Javascript
解决layer弹出层msg的文字不显示的问题
Sep 11 Javascript
vue如何实现动态加载脚本
Feb 05 Javascript
js实现产品缩略图效果
Mar 10 #Javascript
BootStrap注意事项小结(五)表单
Mar 10 #Javascript
微信小程序 弹框和模态框实现代码
Mar 10 #Javascript
BootStrap表单宽度设置方法
Mar 10 #Javascript
Angular.js基础学习之初始化
Mar 10 #Javascript
js实现返回顶部效果
Mar 10 #Javascript
Vue.directive自定义指令的使用详解
Mar 10 #Javascript
You might like
php 修改zen-cart下单和付款流程以防止漏单
2010/03/08 PHP
php学习之数据类型之间的转换介绍
2011/06/09 PHP
php中怎么搜索相关联数组键值及获取之
2013/10/17 PHP
PHP实现QQ快速登录的方法
2016/09/28 PHP
PHP手机短信验证码实现流程详解
2018/05/17 PHP
PHP时间类完整代码实例
2021/02/26 PHP
jQuery 学习第五课 Ajax 使用说明
2010/05/17 Javascript
JavaScript编写页面半透明遮罩效果的简单示例
2016/05/09 Javascript
jquery中的常见问题及快速解决方法小结
2016/06/14 Javascript
jQuery内容过滤选择器用法示例
2016/09/09 Javascript
jQuery ajax请求struts action实现异步刷新
2017/04/19 jQuery
AngularJS  ng-repeat遍历输出的用法
2017/06/19 Javascript
layer子层给父层页面元素赋值,以达到向父层页面传值的效果实例
2017/09/22 Javascript
js和jQuery以及easyui实现对下拉框的指定赋值方法
2018/01/23 jQuery
Vue的轮播图组件实现方法
2018/03/03 Javascript
微信小程序实现拍照画布指定区域生成图片
2019/07/18 Javascript
[54:45]2018DOTA2亚洲邀请赛 4.1 小组赛 A组 Optic vs OG
2018/04/02 DOTA
python ip正则式
2009/05/07 Python
用Python脚本生成Android SALT扰码的方法
2013/09/18 Python
分析Python编程时利用wxPython来支持多线程的方法
2015/04/07 Python
TensorFlow如何实现反向传播
2018/02/06 Python
Python发送邮件测试报告操作实例详解
2018/12/08 Python
pyqt5 删除layout中的所有widget方法
2019/06/25 Python
将python2.7添加进64位系统的注册表方式
2019/11/20 Python
python GUI库图形界面开发之PyQt5打印控件QPrinter详细使用方法与实例
2020/02/28 Python
Python extract及contains方法代码实例
2020/09/11 Python
Jowissa官方网站:瑞士制造的手表,优雅简约的设计
2020/07/29 全球购物
给男朋友的道歉信
2014/01/12 职场文书
石油大学毕业生自荐信
2014/01/28 职场文书
党务公开方案
2014/05/06 职场文书
电力培训心得体会
2014/09/02 职场文书
局领导领导班子四风对照检查材料
2014/09/27 职场文书
党员对照检查剖析材料
2014/10/13 职场文书
2015应届毕业生自荐信范文
2015/03/05 职场文书
实施意见格式范本
2015/06/05 职场文书
财产分割协议书
2016/03/22 职场文书