【WeChat Official Account】WeChat official account page authorization:


When developing a WeChat public account, it is generally necessary to use the WeChat login function. Here, it is necessary to add WeChat authorization to obtain the user's openid (or unionid), and use the openid (or unionid) for unique identification.
[Official account development document] https://developers.weixin.qq.com/doc/

1. Add a business domain name

This is a very important step. The js security domain name configuration configuration is as follows: , select " " to add
登录微信公众号平台->开发->接口权限->网页授权(修改)after entering . Two points are required : 1) The port must be the default port 80, and the added domain name cannot have a port number! (This is stipulated by WeChat) 2). The downloaded txt verification file must be placed in the provided domain name directory. After the configuration is complete, directly access this path in the browser address bar, and it will be successful if it can be opened.js接口安全域名
picture
注意


2. Front-end authorization to obtain code

The first step of WeChat authorization is that the front end obtains the code value returned by WeChat, and passes the code value to the server to obtain the user's openid (or unionid).
Then how to get the code value returned by WeChat?
Use window.location.href to jump to the following link to obtain:

https://open.weixin.qq.com/connect/oauth2/authorize?
appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 
#若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
【1】Parameter description:

APPID: The unique identifier of the official account, the application for the official account has been allocated;
REDIRECT_URL: After successfully getting the code value, you need to jump to the path address of your project, such as login.html; :
SCOPEThere are two fixed values: snsapi_base (silent authorization), snsapi_userinfo (explicit authorization), choose one of the two
STATE; Note that there are format requirements (the state parameter will be included after redirection, and developers can fill in the parameter value of a-zA-Z0-9, up to 128 bytes);

[2] The difference between silent authorization and explicit authorization:

1. Silent authorization: The webpage authorization initiated snsapi_baseby the scope is used to obtain the openid of the user who enters the page, and it is silently authorized and automatically jumps to the callback page. (Another silent type: for the public account that has been followed If the user enters the official account’s web page authorization page from the official account’s session or custom menu, even if the scope is snsapi_userinfo, it is silently authorized, and the user has no perception.)

2. Explicit authorization: The webpage authorization initiated snsapi_userinfoby the scope is used to obtain the basic information of the user. But this kind of authorization requires the user's manual consent for the first time, and since the user has agreed, the basic information of the user can be obtained after authorization without paying attention.

【3】The front end obtains the code of the code:
methods: {
    
    //(以vue为例)
  getCode() {
    
     // 非静默授权,第一次有弹框
    this.code = ''
	var local = window.location.href // 获取页面url
	var appid = 'wx65adcf075369****'
    this.code = this.getUrlCode().code // 截取code
    if (this.code == null || this.code === '') {
    
     // 如果没有code,则去请求
      window.location.href =`https://open.weixin.qq.com/connect/oauth2/authorize?
      appid=${
     
     appid}&redirect_uri=${
     
     encodeURIComponent(local)}&response_type=code&
      scope=snsapi_userinfo&state=123#wechat_redirect`
    } else {
    
    
      // 你自己的业务逻辑
    }
  },
  getUrlCode() {
    
     // 截取url中的code方法
    var url = location.search
    this.winUrl = url
    var theRequest = new Object()
    if (url.indexOf("?") != -1) {
    
    
      var str = url.substr(1)
      var strs = str.split("&")
      for (var i = 0; i < strs.length; i++) {
    
    
        theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
      }
    }
    return theRequest
  }
}
#代码逻辑是先判断有没有code,没有才去获取,使用encodeURIComponent()对回调url进行编码。

3. The backend obtains openid (or unionid)

Here, the front end usually passes the code to the back end, and the back end requests the interface provided by WeChat to obtain the user's openid (or unionid)

【1】Get openid:

The get request interface link is as follows:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

参数说明:
appid is the unique identifier of the official account.
secret is the appsecret code of the official account.
Fill in the code obtained in the first step. The parameter
grant_type is filled in as authorization_code
成功返回数据as follows:

{
    
     
  "access_token":"ACCESS_TOKEN", //接口调用凭证
  "expires_in":7200,//access_token接口调用凭证超时时间,单位(秒)
  "refresh_token":"REFRESH_TOKEN",//用户刷新access_token
  "openid":"OPENID",//授权用户唯一标识
  "scope":"SCOPE"//用户授权的作用域,使用逗号(,)分隔
}
#如果你只需要得到opend_id,这里就结束了。如果需要获取unionid则还需要请求下面接口。
【2】Get unionid

Obtain user information through the returned openid and access_token. The get request interface is as follows:
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

(1) scope is snsapi_userinfo显式授权the returned data as follows:

{
    
    
	"subscribe": 1,//用户是否订阅该公众号标识,值为0时代表此用户没有关注该公众号
	"openid":" OPENID",//用户的标识,对当前公众号唯一
	" nickname": NICKNAME,//用户的昵称
	"sex":"1",//用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
	"language": "zh_CN",//用户的语言,简体中文为zh_CN
	"province":"PROVINCE"//用户所在省份
	"city":"CITY",//用户所在城市
	"country":"COUNTRY",//用户所在国家
	"headimgurl":"http://xxxx/46",//用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
	"subscribe_time": 1382694957,//用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
	"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL",//UnionID 来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号(包括小程序),用户的 UnionID 是唯一的
	"remark": "",//公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
	"groupid": 0,//用户所在的分组ID(兼容旧的用户分组接口)
	"tagid_list":[128,2]  //用户被打上的标签ID列表
}
#ps:需要获取用户信息,必须使用scope为snsapi_userinfo的方式。

(2) scope is snsapi_base静默授权the returned data as follows:

{
    
    
	"subscribe": 0,
	"openid":" OPENID",
	"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}

Fourth, the difference between unionid and openid

If the developer has multiple mobile applications, website applications, and official accounts (including mini programs), the uniqueness of users can be distinguished by unionid, because as long as they are mobile applications, website applications, and official accounts under the same WeChat open platform account (including applets), the user's unionid is unique.
In other words, 同一用户,对同一个微信开放平台下的不同应用,unionid是相同的.

Guess you like

Origin blog.csdn.net/weixin_53791978/article/details/132456652
Recommended