您的位置:首页 > 移动开发 > 微信开发

微信开发笔记——微信网页登录授权,获取用户信息

2014-12-22 15:12 1051 查看
最近做了一个公司的微信的公众号,对微信的流程清楚了不少,这里记录下,算不上多高深的,只希望能帮助到一部分人吧。

我们公司的测试微信公众号:NPCgo 可以感受下,哈哈~~

闲话少说,开始:

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

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

三次握手
微信认证流程(我自己简称三次握手):

1、用户同意授权,获取code

2、通过code换取网页授权access_token,用户openId等信息

3、通过access_token和用户的openId获取该用户的用户信息

思路:

经过研究,我这边的思路是:让所有页面都继承同一个页面,在这个页面里做微信登录授权处理,

因为第一步必须要经过微信的登录授权,不能网页后端请求,所以先要经过用户同意,通过页面网页请求组装的微信请求链接。请求该链接,

获取code后,后端模拟请求。获取用户信息。

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

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 类:

public class WeiXinUserInfo
{
/// <summary>
/// 用户的唯一标识
/// </summary>
public string openid { get; set; }
/// <summary>
/// 用户昵称
/// </summary>
public string nickname { get; set; }
/// <summary>
/// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
/// </summary>
public string sex { get; set; }
/// <summary>
/// 用户个人资料填写的省份
/// </summary>
public string province { get; set; }
/// <summary>
/// 普通用户个人资料填写的城市
/// </summary>
public string city { get; set; }
/// <summary>
/// 国家,如中国为CN
/// </summary>
public string country { get; set; }
/// <summary>
/// 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
/// </summary>
public string headimgurl { get; set; }
/// <summary>
/// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
/// </summary>
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失败");
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: