微信PC授权登录开发

2017/11/26 posted in  微信开发

记录下微信PC授权登录的开发流程

参考资料

开发

基本和公众平台的网页授权差不多

  1. 第一步获取code
  2. 第二步通过code获取access_token
  3. 第三步通过access_token调用接口

在第二步的时候就可以获取到OpenId和unionid,由于我这次只需要Openid,所以我只做到了第二步。另外经测试通过开放平台微信授权获取到的OpenId和通过公众平台获取到的OpenId不一样。

代码示例

public class QrCodeLogin
{
    static RandomHelper randomHelper = new RandomHelper();

    /// <summary>
    /// </summary>
    /// <param name="appId">开放平台网站应用AppId</param>
    /// <param name="redirectUri">回调地址</param>
    /// <param name="state">用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验</param>
    /// <returns></returns>
    public static string GetToCodeUrl(string appId, string redirectUri, string state = "")
    {
        CookieHelper.UpdateCookie("QrCodeLoginState", string.IsNullOrEmpty(state) ? randomHelper.GenerateCheckCode(30) : state);
        return string.Format("https://open.weixin.qq.com/connect/qrconnect?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_login&state={2}#wechat_redirect", appId, HttpUtility.UrlEncode(redirectUri), state);
    }

    private string _appId;
    private string _appSecret;
    public QrCodeLogin(string appid, string appSecret)
    {
        _appId = appid;
        _appSecret = appSecret;
    }

    public AjaxResult Login(ControllerContext context, Action<WxUserInfo, string> action)
    {
        string code = context.HttpContext.Request.QueryString["code"];
        string state = context.HttpContext.Request.QueryString["state"];

        string oldState = CookieHelper.GetCookie("QrCodeLoginState");
        if (oldState.IsEmpty() || oldState != state)
            return new AjaxResult("参数异常");


        CookieHelper.RemoveCookie("QrCodeLoginState");
        string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", _appId, _appSecret, code);
        string result = HttpHelper.Get(url);
        if (result.IsEmpty()) return new AjaxResult("获取Token结果为空");
        JObject o = JObject.Parse(result);
        if (o == null) return new AjaxResult("获取Token,序列化请求结果出错:" + result);


        OrCodeLoginConfig config = new OrCodeLoginConfig
        {
            AccessToken = o.GetValue("access_token").ToString(),
            ExpiresIn = o.GetValue("expires_in").ToString().ToInt(),
            RefreshToken = o.GetValue("refresh_token").ToString()
        };

        WxUserInfo wxUserInfo = new WxUserInfo
        {
            OpenId = o.GetValue("openid").ToString(),
            UnionId = o.GetValue("unionid").ToString()
        };
        action.Invoke(wxUserInfo, state);
        return new AjaxResult(true);
    }
}

调用

public ActionResult WxQrCodeLoginBind()
{
    QrCodeLogin login = new QrCodeLogin("*****", "*****");
    AjaxResult result = login.Login(ControllerContext, (uInfo, state) =>
    {
        Models.Account.User.User user = userService.GetByNum(state);
        if (user != null)
        {
            user.WxUid = uInfo.UnionId;
            userService.Update(user);
        }
    });

    if (result.IsSuccess)
    {
        return Redirect("~/User/Login");
    }
    return Content(result.Message);
}

项目用的.net mvc 4.0开发
以上就是这次微信开放平台网站授权登录开发总结,如有不对,欢迎来信指正。