微信開發筆記——微信網頁登陸受權,獲取用戶信息

原文地址:http://www.cnblogs.com/woaic/p/weixin-login.htmlhtml

 

最近作了一個公司的微信的公衆號,對微信的流程清楚了很多,這裏記錄下,算不上多高深的,只但願能幫助到一部分人吧。數據庫

咱們公司的測試微信公衆號:NPCgo 能夠感覺下,哈哈~~json

閒話少說,開始:後端

首先你們要看下微信的API文檔。api

微信網頁受權,獲取用戶的微信官方API文檔地址:
http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html微信

三次握手
微信認證流程(我本身簡稱三次握手):
一、用戶贊成受權,獲取code
二、經過code換取網頁受權access_token,用戶openId等信息
三、經過access_token和用戶的openId獲取該用戶的用戶信息app

思路:
通過研究,我這邊的思路是:讓全部頁面都繼承同一個頁面,在這個頁面裏作微信登陸受權處理,
由於第一步必需要通過微信的登陸受權,不能網頁後端請求,因此先要通過用戶贊成,經過頁面網頁請求組裝的微信請求連接。請求該連接,
獲取code後,後端模擬請求。獲取用戶信息。dom

微信三次握手的方法(代碼)post

複製代碼
public class WeiXinOAuth
{
    /// <summary>
    /// 獲取微信Code
    /// </summary>
    /// <param name="appId"></param>
    /// <param name="appSecret"></param>
    /// <param name="redirectUrl"></param>
    public string GetWeiXinCode(string appId,string appSecret,string redirectUrl)
    {
        Random r = new Random();
        //微信登陸受權
        //string url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        //微信OpenId受權
        //string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + redirectUrl +"&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        //微信用戶信息受權
        string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

        return url;
    }
    /// <summary>
    /// 經過code獲取access_token
    /// </summary>
    /// <param name="appId"></param>
    /// <param name="appSecret"></param>
    /// <param name="code"></param>
    /// <returns></returns>
    public Model.WeiXinAccessTokenResult GetWeiXinAccessToken(string appId,string appSecret,string code)
    {
        string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+
            "&code="+ code + "&grant_type=authorization_code";
        string jsonStr = Tools.GetHttpRequest(url);

        Model.WeiXinAccessTokenResult result = new Model.WeiXinAccessTokenResult();
        if (jsonStr.Contains("errcode"))
        {
            Model.WeiXinErrorMsg errorResult = new Model.WeiXinErrorMsg();
            errorResult=JsonHelper.ParseFromJson<Model.WeiXinErrorMsg>(jsonStr);
            result.ErrorResult = errorResult;
            result.Result = false;
        }
        else
        {
            Model.WeiXinAccessTokenModel model = new Model.WeiXinAccessTokenModel();
            model = JsonHelper.ParseFromJson<Model.WeiXinAccessTokenModel>(jsonStr);
            result.SuccessResult = model;
            result.Result = true;
        }
        return result;
    }
    /// <summary>
    /// 拉取用戶信息
    /// </summary>
    /// <param name="accessToken"></param>
    /// <param name="openId"></param>
    /// <returns></returns>
    public Model.WeiXinUserInfoResult GetWeiXinUserInfo(string accessToken,string openId)
    {
        string url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";

        string jsonStr = Tools.GetHttpRequest(url);
        Model.WeiXinUserInfoResult result = new Model.WeiXinUserInfoResult();
        if(jsonStr.Contains("errcode"))
        {
            Model.WeiXinErrorMsg errorResult = new Model.WeiXinErrorMsg();
            errorResult = JsonHelper.ParseFromJson<Model.WeiXinErrorMsg>(jsonStr);
            result.ErrorMsg = errorResult;
            result.Result = false;
        }
        else
        {
            Model.WeiXinUserInfo userInfo = new Model.WeiXinUserInfo();
            userInfo = JsonHelper.ParseFromJson<Model.WeiXinUserInfo>(jsonStr);
            result.UserInfo = userInfo;
            result.Result = true;
        }
        return result;
    }
}
複製代碼

所須要的對應實體類測試

WeiXinAccessTokenResult 類:

  View Code
WeiXinAccessTokenModel類:
  View Code
WeiXinErrorMsg類:
  View Code
WeiXinUserInfoResult類:
 
  View Code
WeiXinUser 類 :
  View Code
全部的頁面,都會繼承BasePage頁面,這樣方便處理,繼承這個頁面的其餘頁面就不須要考慮認證的問題了。
複製代碼
public partial class BasePage : System.Web.UI.Page
{
    public BasePage()
    {
        this.Page.Load += new EventHandler(Page_Load);
        this.Page.Unload += new EventHandler(Page_UnLoad);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DoWith();
    }

    protected void Page_UnLoad(object sender, EventArgs e)
    {
    }
    private void DoWith()
    {
        //用戶還沒有登陸
        if (BLL.UserInfoManager.Instance().GetUserId() <= 0)
        {
            //獲取appId,appSecret的配置信息
            string appId = System.Configuration.ConfigurationSettings.AppSettings["appid"];
            string appSecret = System.Configuration.ConfigurationSettings.AppSettings["secret"];
            Core.WeiXinOAuth weixinOAuth = new WeiXinOAuth();
            //微信第一次握手後獲得的code 和state
            string _code = Cmn.Request.Get("code");
            string _state = Cmn.Request.Get("state");

            if (_code == "" || _code == "authdeny")
            {
                if (_code == "")
                {
                    //發起受權(第一次微信握手)
                    string _authUrl = weixinOAuth.GetWeiXinCode(appId, appSecret, HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.ToString()));
                    HttpContext.Current.Response.Redirect(_authUrl, true);
                }
                else
                { // 用戶取消受權
                    HttpContext.Current.Response.Redirect("~/Error.html", true);
                }
            }
            else
            {
                //獲取微信的Access_Token(第二次微信握手)
                Core.Model.WeiXinAccessTokenResult modelResult = weixinOAuth.GetWeiXinAccessToken(appId, appSecret, _code);

                //獲取微信的用戶信息(第三次微信握手)
                Core.Model.WeiXinUserInfoResult _userInfo = weixinOAuth.GetWeiXinUserInfo(modelResult.SuccessResult.access_token,modelResult.SuccessResult.openid);

                //用戶信息(判斷是否已經獲取到用戶的微信用戶信息)
                if (_userInfo.Result && _userInfo.UserInfo.openid != "")
                {
                    //保存獲取到的用戶微信用戶信息,並保存到數據庫中
                }
                else
                {
                    GameTradingByPublic.ExceptionLog.writeFile(2, "獲取用戶OpenId失敗");
                }
            }
        }
    }
}
複製代碼

 

 
分類:  .NET開發
相關文章
相關標籤/搜索