一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net版微信网页登录授权,获取用户信息例子

时间:2022-06-25 03:34:52 编辑:袖梨 来源:一聚教程网


asp.net版微信网页登录授权必须要是微信公众号并且类型为“服务号”

首先大家要看下微信的API文档。

微信网页授权,获取用户的微信官方API文档地址:
http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html


微信认证流程:

1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
5 附:检验授权凭证(access_token)是否有效

思路:

经过研究,我这边的思路是:让所有页面都继承同一个页面,在这个页面里做微信登录授权处理,
因为第一步必须要经过微信的登录授权,不能网页后端请求,所以先要经过用户同意,通过页面网页请求组装的微信请求链接。请求该链接,
获取code后,后端模拟请求。获取用户信息。

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

public class WeiXinOAuth
{
    ///


    /// 获取微信Code
    ///

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


    /// 通过code获取access_token
    ///

    ///
    ///
    ///
    ///
    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(jsonStr);
            result.ErrorResult = errorResult;
            result.Result = false;
        }
        else
        {
            Model.WeiXinAccessTokenModel model = new Model.WeiXinAccessTokenModel();
            model = JsonHelper.ParseFromJson(jsonStr);
            result.SuccessResult = model;
            result.Result = true;
        }
        return result;
    }
    ///


    /// 拉取用户信息
    ///

    ///
    ///
    ///
    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(jsonStr);
            result.ErrorMsg = errorResult;
            result.Result = false;
        }
        else
        {
            Model.WeiXinUserInfo userInfo = new Model.WeiXinUserInfo();
            userInfo = JsonHelper.ParseFromJson(jsonStr);
            result.UserInfo = userInfo;
            result.Result = true;
        }
        return result;
    }
}
所需要的对应实体类

WeiXinAccessTokenResult 类:

微信开发笔记——微信网页登录授权,获取用户信息
微信开发笔记——微信网页登录授权,获取用户信息
public class WeiXinAccessTokenResult
{
    public WeiXinAccessTokenModel SuccessResult { get; set; }
    public bool Result { get; set; }

    public WeiXinErrorMsg ErrorResult { get; set; }

}
View Code
WeiXinAccessTokenModel类:
微信开发笔记——微信网页登录授权,获取用户信息
微信开发笔记——微信网页登录授权,获取用户信息
///


/// 通过code获取access_token 请求成功的实体
///

public class WeiXinAccessTokenModel
{
    ///
    /// 接口调用凭证
    ///

    public string access_token { get; set; }
    ///
    /// access_token接口调用凭证超时时间,单位(秒)
    ///

    public int expires_in { get; set; }
    ///
    /// 用户刷新access_token
    ///

    public string refresh_token { get; set; }
    ///
    /// 授权用户唯一标识
    ///

    public string openid { get; set; }
    ///
    /// 用户授权的作用域,使用逗号(,)分隔
    ///

    public string scope { get; set; }
}
View Code
WeiXinErrorMsg类:
微信开发笔记——微信网页登录授权,获取用户信息
微信开发笔记——微信网页登录授权,获取用户信息
///
/// 微信错误访问的情况
///

public class WeiXinErrorMsg
{
    ///
    /// 错误编号
    ///

    public int errcode { get; set; }
    ///
    /// 错误提示消息
    ///

    public string errmsg { get; set; }
}
View Code
WeiXinUserInfoResult类:
 
微信开发笔记——微信网页登录授权,获取用户信息
微信开发笔记——微信网页登录授权,获取用户信息
///
/// 获取微信用户信息
///

public class WeiXinUserInfoResult
{
    ///
    /// 微信用户信息
    ///

    public WeiXinUserInfo UserInfo { get; set; }
    ///
    /// 结果
    ///

    public bool Result { get; set; }
    ///
    /// 错误信息
    ///

    public WeiXinErrorMsg ErrorMsg { get; set; }
}
View Code
WeiXinUser 类 :
微信开发笔记——微信网页登录授权,获取用户信息
微信开发笔记——微信网页登录授权,获取用户信息
public class WeiXinUserInfo
{
    ///
    /// 用户的唯一标识
    ///

    public string openid { get; set; }
    ///
    /// 用户昵称
    ///

    public string nickname { get; set; }
    ///
    /// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
    ///

    public string sex { get; set; }
    ///
    /// 用户个人资料填写的省份
    ///

    public string province { get; set; }
    ///
    /// 普通用户个人资料填写的城市
    ///

    public string city { get; set; }
    ///
    /// 国家,如中国为CN
    ///

    public string country { get; set; }
    ///
    /// 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
    ///

    public string headimgurl { get; set; }
    ///
    /// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
    ///

    public string[] privilege { get; set; }
}
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失败");
                }
            }
        }
    }
}

热门栏目