微信开发之微信网页授权获取用户openId

开发场景:
在微信客户端打开某个网页可以获取到用户的openId。

获取用户openid步骤如下:参考微信公众平台开发文档

第一步:引导微信公众平台的用户打开如下链接

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
参数说明

参数               是否必须   说明
appid               是      公众号的唯一标识
redirect_uri        是      授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
response_type       是      返回类型,请填写code
scope               是      应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),     snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
state               否      重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect    是      无论直接打开还是做页面302重定向时候,必须带此参数
参考链接(请在微信客户端中打开此链接体验):
scope为snsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
scope为snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

注意事项:
1、redirect_uri 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理。进行urlEncode处理戳这里
2、appid必须是服务号的开发者ID(订阅号是没有权限通过网页授权来获取用户基本信息的),并且该服务号开通了微信网页授权的功能,且配置了微信授权回调域名,这样才能获取到code码用于进一步获取用户openid。(微信公众号的区分–服务号和订阅号有何不同?
如下图:
这里写图片描述
这里写图片描述

第二步:在重定向的回调页面(redirect_uri)里获取code,并请求openid

    // 获取code   
    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;
        }
    var code = getQueryString("code");  
    alert(code)   // 获取code值可以在客户端打开链接的时候alert出来查看
    // 请求openid
    $.ajax({ 
      async: false, 
      url: "http://api.xxx.com/member/platformDict/getOpenId", //后端提供的获取openid的接口
      type: "GET", 
      data: {code:code}, //传递本页面获取的code到接口,以便获取openid
      timeout: 5000, 
      success: function (result) { 
        // 根据后台接口返回的参数 result里应该会包含openid,就可以获取到了
      }, 
      error: function (jqXHR, textStatus, errorThrown) { 
          alert(textStatus); 
      } 
  })
</script>

code

猜你喜欢

转载自blog.csdn.net/one_girl/article/details/80018860