• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

微信小程序登录

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
App({
    onLaunch: function () {
        wx.login({
          success: function (res) {
            if (res.code) {
              var code = res.code;
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              console.log(\'获取用户登录凭证:\' + code);
              // --------- 发送凭证 ------------------
              wx.request({
                url: webserveurl,
                data: { action: "onlogin", code: code },
                header: {
                  \'content-type\': \'application/json\' // 默认值
                },
                success: function (res) {
                  console.log("wx.request-onlogin-" + JSON.stringify(res));
                  if (res.data.errcode == 0) {
                    wx.setStorageSync(\'openid\', res.data.data.openid);

                    var userid = res.data.data.userid;
                    if (userid > 0) {//已经有账号
                      wx.setStorageSync(\'userid\', userid);
                    } else {//游客
                      getUserInfo();
                    }
                  } else {
                    console.log("登录失败");
                  }
                }
              });
              // ------------------------------------
            } else {
              console.log(\'获取用户登录态失败!\' + res.errMsg)
            }
          }
        });
    },
    //全局获取openid的方法
    getOpenId: function () {
        return wx.getStorageSync(\'openid\');
    },
    //全局获取openid的方法
    getUserId: function () {
        return wx.getStorageSync(\'userid\');
    }
})
wx.login登录
private string OnLogin(HttpContext context)
{
    string code = context.Request.Params["code"];
    string retString = string.Empty;
    string formatString = string.Format(@"https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", appid, appsecret, code);
    try
    {
        retString = weixinbase.RequestGetUrl(formatString);
        #region 正常返回的JSON数据包
        ////正常返回的JSON数据包
        //{
        //    "openid": "OPENID",
        //    "session_key": "SESSIONKEY",
        //}
        ////满足UnionID返回条件时,返回的JSON数据包
        //{
        //    "openid": "OPENID",
        //    "session_key": "SESSIONKEY",
        //    "unionid": "UNIONID"
        //}
        ////错误时返回JSON数据包(示例为Code无效)
        //{
        //    "errcode": 40029,
        //    "errmsg": "invalid code"
        //} 
        #endregion
        ResultMsg relust = JsonConvert.DeserializeJsonToObject<ResultMsg>(retString);
        //开发者应该事先通过 wx.login 登录流程获取会话密钥 session_key 并保存在服务器。为了数据不被篡改,开发者不应该把session_key传到小程序客户端等服务器外的环境。
        if (relust.errcode == 0)
        {
            Model.TUser mod = bll_TUser.GetModelByOpenId(relust.openid) ?? new Model.TUser();
            int userid = mod != null ? mod.ID : 0;
            //保存登录状态
            context.Cache.Insert("USERModel_" + relust.openid, mod);
            //保存openid session_key
            context.Cache.Insert("session_key_" + relust.openid, relust.session_key);
            return "{\"errcode\": 0, \"errmsg\": \"登录成功!\", \"data\":{\"userid\": \"" + userid + "\",\"openid\": \"" + relust.openid + "\"}}";
        }
        else
        {
            return "{\"errcode\": " + relust.errcode + ", \"errmsg\": \"" + relust.errmsg + "\", \"data\":[]}";
        }
    }
    catch (Exception ex)
    {
        return "{\"errcode\": -2, \"errmsg\": \"" + ex.StackTrace + "\", \"data\":[]}";
    }
}

/// <summary>
/// 结果信息
/// </summary>
public class ResultMsg
{
    /// <summary>
    /// 错误码
    /// </summary>
    public int errcode;
    /// <summary>
    /// 错误信息
    /// </summary>
    public string errmsg;
    /// <summary>
    /// 用户唯一标识
    /// </summary>
    public string openid;
    /// <summary>
    /// 会话密钥
    /// </summary>
    public string session_key;
    /// <summary>
    /// 用户在开放平台的唯一标识符
    /// </summary>
    public string unionid;
}
使用 临时登录凭证code 获取 session_key 和 openid 等
function getUserInfo() {
  //获取游客具体敏感信息
  wx.getUserInfo({
    success: function (res) {
      console.log("获取用户信息成功-" + JSON.stringify(res))
      //后续处理--解密游客具体信息
      getEncrypUserInfo(res.signature, res.encryptedData, res.iv)
    },
    fail: function (res) {
      console.log("获取用户信息失败-" + JSON.stringify(res))
    }
  });
}
wx.getUserInfo获取游客具体敏感信息
//解密用户数据
function getEncrypUserInfo(signature, encryptedData, iv) {
  wx.request({
    url: webserveurl,
    data: { action: "getencrypuserinfo", "signature": signature, "encryptedData": encryptedData, "iv": iv, "openid": wx.getStorageSync(\'openid\') },
    success: function (res) {
      console.log("getEncrypUserInfo-" + JSON.stringify(res));
    }
  });
}
wx.request解密用户数据
/// <summary>
/// 解密微信wx.getUserInfo返回的 用户敏感数据
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private string GetEncrypUserInfo(HttpContext context)
{
    string openid = context.Request.Params["openid"];
    string signature = context.Request.Params["signature"];
    string encryptedData = context.Request.Params["encryptedData"];
    string iv = context.Request.Params["iv"];
    string session_key = context.Cache["session_key_" + openid] == null ? "error" : context.Cache["session_key_" + openid].ToString();
    string result = AESDecrypt(encryptedData, iv, session_key);
    result = result.Length > 0 ? result : "{\"errcode\":\"0\",\"errmsg\":\"无效数据\"}";
    return result;
}

/// <summary>
/// AES-128-CBC对称解密
/// </summary>
/// <param name="encryptedData"></param>
/// <param name="iv"></param>
/// <param name="session_key"></param>
/// <returns></returns>
private string AESDecrypt(string encryptedData, string iv, string session_key)
{
    string result = string.Empty;
    try
    {
        byte[] encryptedDataBytes = Convert.FromBase64String(encryptedData);
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        rijndaelCipher.Key = Convert.FromBase64String(session_key);
        rijndaelCipher.IV = Convert.FromBase64String(iv);
        rijndaelCipher.Mode = CipherMode.CBC;
        rijndaelCipher.Padding = PaddingMode.PKCS7;
        ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
        byte[] plainText = transform.TransformFinalBlock(encryptedDataBytes, 0, encryptedDataBytes.Length);
        result = Encoding.UTF8.GetString(plainText);
    }
    catch (Exception e)
    {
        Log.Error("AESDecrypt-" + e.ToString());
    }
    return result;
}
AES-128-CBC对称解密

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
微信小程序登录流程发布时间:2022-07-18
下一篇:
微信小程序 - 实现简单登录和个人信息页面发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap