微信开发——网页H5受权,获取微信用户资料

微信H5开发详细配置

1.配置公众号受权域名

设置网页受权域名,为服务器绑定的域名,微信内页面受权必须在这个域名下html

注意:配置好后,下载微信网页受权文本文件.`MP_verify_xxxxx`放到服务器程序的根目录,当你提交的时候,微信会去认证,没有这个文件,微信这一步认证不会经过。 ajax

配置Token认证,微信将和你的服务器进行第一次的校验

微信的服务器配置启用,Url须要注意,微信会post参数:echoStr,signature,nonce等到你填写的url地址去访问,就是一次验证,服务器是否经过。 注意这里请求的本身的Url返回值须要是“echoStr”,注意返回的mediaType要是”text/html”类型,纯文本字符串响应给微信。 像`ASP.NET MVC`里面直接`return Content("")`就行. 后端

服务端示例代码api

[Route("gateway")]
public HttpResponseMessage Gateway()
{
    string echoString = HttpContext.Current.Request.QueryString["echoStr"];
    string signature = HttpContext.Current.Request.QueryString["signature"];
    string nonce = HttpContext.Current.Request.QueryString["nonce"];
    HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(echoString, Encoding.GetEncoding("UTF-8"), "text/html") };
    return result;
}
复制代码

点此参考微信网页受权文档浏览器

2.配置请求网页的地址

公众号菜单配置缓存

"sub_button": [
    {
        "type": "view", 
        "name": "订票系统", 
        "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx79a3d1c56ecf560c&redirect_uri=http://{你微信服务器配置的域名}/ticketSys/Home/Index&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"
    }
]
复制代码

或者直接在微信里面访问网页能够行,只要你微信公众号配置经过了 https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx79a3d1c56ecf560c&redirect_uri=http://{你微信服务器配置的域名}/ticketSys/Home/Index&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirectbash

3.访问地址,容许受权,获取用户信息

当咱们在微信访问配置的redirect_uri跳转的页面,如:www.testxx.com,会弹出绑定的微信公众号信息,让你受权服务器

点击容许后,微信将页面再次跳转到redirect_uri/?code={Code}&state={State}微信

赞成受权后,微信会回传一个code值到按钮指定的uri中去,code做为换取token的票据,每次用户受权带上的code不同,code只能使用一次,5分钟过时。app

回调的连接以下,在指定的redirect_uri上加了参数,而且微信浏览器把当前url改变了,能够经过location.href查看到当前的url

当咱们拿到Code的时候,须要再次请求一下咱们配置的主页(redirect里面的uri),以便后台接收到Code,经过Code去获取访问凭据和用户信息。很是重要!

如:http://www.testxx.cn/Home/Index 就是从新调用一下咱们按钮中配置的,js在页面加载完毕事件写:

var vCode = getQueryString("code");
 if (vCode != "" && vCode != null) {  //微信回调页面传递的code,须要本身再拿到后台去校验获取用户数据
     $.ajax({
         url: '/weixin/user/' + vCode,
         type: 'get'
     }).done(function (data) {
         // 获取到微信用户资料存储到缓存中
         localStorage.setItem('wxUser', JSON.stringify(data.data));
     });
 }
 else {
     // 没有code再跳转一次,防止没有进行受权(OpenId),获取不到用户信息。
     location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + wxRedirectUri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
 }
 ...
 
 //获取url的参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
复制代码

后端MVC代码(仅供参考)

[HttpGet]
public async Task<ActionResult> Index()
{
    //用户赞成受权会回调该页面,获取code,code只能使用一次,5分钟过时
    string code = Request["code"];
    if (!string.IsNullOrEmpty(code))
    {
        Session["code"] = code;
    }
    string appId = WxPayConfig.APPID;
    string appSecret = WxPayConfig.APPSECRET;
    WeiXinUser wxUser = await WeiXinHelper.GetWxUserByCode(appId, appSecret, code);
    wxUser.AppId = appId;
    Session["openid"] = wxUser.OpenId;
    return View(wxUser);
}
复制代码

注:WeiXinHelper.GetWxUserByCode这是本身封装的方法,就是根据code去换取微信access_token,微信官方接口:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

如上就能够获取到已受权的微信用户基本信息了,包含昵称、地区、性别、头像。

相关文章
相关标签/搜索