PHP implements WeChat web page login authorization development
不言
Release: 2023-03-24 12:36:01
Original
14777 people have browsed it
This article mainly introduces the implementation of WeChat web page login authorization development with PHP. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
WeChat open platform and the public The difference between platforms
1. The public platform is oriented to ordinary users, such as self-media and media, and is used by the company’s official WeChat public account operators. Of course, your team or company has the strength to develop some Content can also call interfaces in the public platform, such as custom menus, automatic replies, and query functions. At present, most WeChat are doing this after passing the certification.
mp.weixin.qq.com
2. The open platform is for developers and third-party independent software developers. I think the biggest openness of the development platform is WeChat login. At that time, Tencent did not make great efforts to implement unified login. As a result, each website now has to develop a login mechanism. Fortunately, they now understand the situation. Developers or software developers, through the platform and interface provided by WeChat, can develop e-commerce websites suitable for enterprises, scan the QR code to enter a game interface, and then purchase goods. Of course, the subsequent open platform will open the payment interface, so software developers such as Pocket Tong can provide services and software such as WeChat stores for large and small and medium-sized enterprises.
open.weixin.qq.com
The public platform is the management and development backend for service account subscription accounts.
To put it simply, the development platform is to realize the one-click sharing of the content of the software installed in the mobile phone to the circle of friends;
The following third-party login relies on the open platform (open.weixin.qq.com ) Function
Preparation work
Website application WeChat login is a WeChat OAuth2.0 authorized login system built based on the OAuth2.0 protocol standard.
Before performing WeChat OAuth2. Before performing WeChat OAuth2.0 authorized login and access, register a developer account on the WeChat open platform, have an approved website application, and obtain the corresponding AppID and AppSecret. After applying for WeChat login and passing the review, you can start the access process.
Authorization process description
WeChat OAuth2.0 authorized login allows WeChat users to use their WeChat identity to securely log in to third-party applications or websites, and the WeChat user authorizes to log in to third parties that have accessed WeChat OAuth2.0 After application, the third party can obtain the user's interface calling credentials (access_token), and use the access_token to call the WeChat open platform authorization relationship interface, thereby obtaining the basic open information of WeChat users and helping users realize basic open functions.
WeChat OAuth2.0 authorized login currently supports authorization_code mode, which is suitable for application authorization with server side. The overall process of this model is:
1. A third party initiates a WeChat authorized login request. After the WeChat user allows authorization of the third-party application, WeChat will launch the application or redirect to the third-party website, and bring the authorization temporary ticket. code parameter;
2. Add AppID and AppSecret through the code parameter, and exchange access_token through API;
3. Make interface calls through access_token to obtain the user's basic data resources or help the user achieve basic operate.
Get access_token sequence diagram:
Step 1: Request CODE
Third party use website application authorization Before logging in, please note that you have obtained the corresponding web page authorization scope (scope=snsapi_login), you can open the following link on the PC: https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri= REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
If it prompts "The link cannot be accessed", please check whether the parameters are filled in incorrectly. For example, the domain name of redirect_uri is inconsistent with the authorized domain name filled in during the review or the scope is not snsapi_login.
Parameters
##Is it required
Description
##appid
is
Application Unique Identifier
redirect_uri
is
Redirect address needs UrlEncode
response_type
is
Fill in the code
scope
is
Application authorization scope, multiple scopes are separated by commas (,), web applications currently only need to fill in snsapi_login
state
no
Used to maintain the status of requests and callbacks, and bring them back to the third party as they are after authorizing the request. This parameter can be used to prevent CSRF attacks (cross-site request forgery attacks). It is recommended that third parties bring this parameter. It can be set to a simple random number plus session for verification
Parameter description
Return description
After the user allows authorization, it will be redirected to the redirect_uri URL with the code and state parameters
redirect_uri?code=CODE&state=STATE
If the user prohibits authorization, the code parameter will not be carried after redirection, only the state parameter will be carried
redirect_uri?state =STATE
Request example
Log in to Yihaodian website application
https://passport.yhd.com/wechat/login.do
After opening, Yihaodian will generate the state parameter and jump to https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https://passport.yhd.com/wechat /callback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect
The second way to obtain the code supports the website to log in to WeChat in 2D The code is embedded into the own page, and the user uses WeChat to scan the code for authorization and returns the code to the website through JS.
The main purpose of JS WeChat login: The website hopes that users can complete the login within the website without jumping to the WeChat domain to log in and then return, to improve the fluency and success rate of WeChat login. How to implement JS for WeChat login with QR code embedded in the website:
Step 1: First introduce the following JS file into the page (https is supported):
Step 2: Instance the following JS object where WeChat login is required:
The container id of the QR code displayed on the third-party page
##appid
is
The unique identification of the application will be obtained after submitting the application for review on the WeChat open platform.
scope
is the
application authorization scope. Multiple scopes are separated by commas (,). For web applications, currently you only need to fill in snsapi_login
redirect_uri
is the
redirection address and needs to be UrlEncode
state
No
is used to maintain the status of the request and callback, after authorizing the request Bring it back to the third party as is. This parameter can be used to prevent CSRF attacks (cross-site request forgery attacks). It is recommended that third parties bring this parameter. It can be set to a simple random number plus session for verification
style
No
Provide "black" and "white" options, and the default is black text description. For details, see FAQ
href
##No
##Since Define style links, and third parties can override the default style according to actual needs. For details, see FAQ
Access_token interface call credential timeout, unit (second)
refresh_token
User refresh access_token
##openid
Unique identification of authorized users
##scope
The scope of user authorization, use commas ( ,) separated
## unionid
Only after the user binds the official account to the WeChat open platform account, This field appears.
Error return example:
{"errcode":40029,"errmsg":"invalidcode"}
Refresh the access_token validity periodAccess_token is the calling credential for calling the authorization relationship interface. Since the access_token validity period (currently 2 hours) is short, when the access_token times out, you can use refresh_token to refresh, access_token There are two refresh results:
1. If the access_token has timed out, then refresh_token will get a new access_token with a new timeout time;
2. If the access_token has not timed out, then refresh_token The access_token will not be changed, but the timeout will be refreshed, which is equivalent to renewing the access_token. refresh_token has a long validity period (30 days). When the refresh_token expires, the user needs to re-authorize it. Request methodAfter obtaining the code of the first step, request the following link for refresh_token: https://api.weixin.qq.com/sns/oauth2/ refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKENParameter description##Parameter
Is it necessary
Description
appid
is the
application unique identifier
##grant_type
Yes
##Fill in refresh_token
##refresh_token
Yes
Fill in the refresh_token parameter obtained through access_token
1. Appsecret is the key used by the application interface. If leaked, it may lead to application data leakage, application High-risk consequences such as user data leakage; stored on the client, it is very likely to be maliciously stolen (such as decompiling to obtain the Appsecret);
2. Access_token is the credential for users to authorize third-party applications to initiate interface calls (equivalent to (in user login state), stored on the client, user data may be leaked after maliciously obtaining access_token, user WeChat related interface functions may be maliciously initiated, etc.;
3. refresh_token is used to authorize third-party applications for users. Long-term credentials are only used to refresh access_token, but if leaked, it will be equivalent to access_token leakage, and the risk is the same as above.
It is recommended to put the secret and user data (such as access_token) on the App cloud server, and the cloud transfer interface calls the request.
Step 3: Call the interface through access_token
After obtaining the access_token, make the interface call with the following prerequisites:
1. The access_token is valid and has not expired;
2. The WeChat user has authorized the corresponding interface scope (scope) of the third-party application account.
For interface scope (scope), the interfaces that can be called are as follows:
Authorization scope (scope)
Interface
Interface Description
snsapi_base
/sns/oauth2/access_token
Exchange code for access_token, refresh_token and authorized scope
/sns/oauth2/refresh_token
Refresh or renew access_token use
/sns/auth
Check access_token validity
##snsapi_userinfo
/sns/userinfo
Get user personal information
Among them, snsapi_base belongs to the basic interface. If the application already has other scope permissions, it will have the permissions of snsapi_base by default. Using snsapi_base can allow mobile web page authorization to bypass the action of jumping to the authorization login page to request user authorization, and directly jump to the third-party web page with the authorization temporary ticket (code), but this will make the user's authorized scope (scope) only snsapi_base , resulting in the inability to obtain data and basic functions that require user authorization.
F.A.Q
1. What is an authorization temporary ticket (code)?
Answer: A third party needs to use the code to obtain the access_token. The timeout of the code is 10 minutes. A code can only be successfully exchanged for the access_token once and then it will become invalid. The temporary and one-time nature of the code ensures the security of WeChat authorized login. Third parties can further enhance the security of their own authorized logins by using https and state parameters.
2. What is authorization scope?
Answer: Authorization scope (scope) represents the interface permissions authorized by users to third parties. Third-party applications need to apply to the WeChat open platform for permission to use the corresponding scope, and then use the method described in the document to allow users to authorize. After user authorization, the interface can be called only after obtaining the corresponding access_token.
3. What is the role of the style field in the WeChat login JS code embedded in the website?
Answer: The color style of the third-party page may be light or dark. If the third-party page has a light background, the style field should provide a "black" value (or not, black is the default value), then The corresponding WeChat login text style is black. The related effects are as follows:
If the "white" value is provided, the corresponding text description will be displayed in white, suitable for dark backgrounds. The relevant effects are as follows:
4. What is the role of the href field in the WeChat login JS code with a QR code embedded in the website?
Answer: If a third party feels that the default style provided by the WeChat team does not match its own page style, it can provide its own style file to override the default style. For example, if a third party feels that the default QR code is too large, it can provide relevant css style files and fill in the link address into the href field
This interface is used to obtain user personal information. Developers can obtain basic user information through OpenID. It is particularly important to note that if a developer has multiple mobile applications, website applications and public accounts, the user can be uniquely distinguished by obtaining the unionid in the user’s basic information, because as long as they are mobile applications under the same WeChat open platform account , website applications and public accounts, the user's unionid is unique. In other words, for the same user, the unionid is the same for different applications under the same WeChat open platform.
The identification of an ordinary user, unique to the current developer account
nickname
Normal user nickname
sex
Normal user gender, 1 is male, 2 is female
province
Province filled in the personal data of ordinary users
city
City filled in the personal data of ordinary users
country
Country, such as China is CN
headimgurl
User avatar, the last value represents the square avatar size (there are 0, 46, 64, 96, 132 values available, 0 represents a 640*640 square avatar ), this item is empty when the user does not have an avatar
privilege
User privilege information, json array, such as WeChat Woka user is (chinaunicom)
unionid
user unified identification. For applications under a WeChat open platform account, the unionid of the same user is unique.
Wrong Json return example:
{
"errcode":40003,"errmsg":"invalid openid "}<br/><br/>Call frequency limit
For a certain service, including mobile app, PC web page, and public account service, what is the data flow process for users to log in with WeChat authorization?
1. The user authorizes the mobile app service through WeChat; the application service can obtain the user's union id through the interface. At this time, if the id is not found in the database, it will be identified as a new user and a user will be created directly. id, the unique user id corresponds to the union id;
2. The user scans the WeChat QR code on the PC side to authorize joint login to obtain the PC side service; the application service can obtain the user's union id through the interface. At this time, If this ID is found in the database, the PC login account will be merged into the unique user ID account created before;
3. The user can log in to the public account service with WeChat authorization by following the public account of the service. ;The application server can obtain the user's union id through the interface. At this time, if the id is found in the database, the account logged in from the official account will be merged into the unique user id account created before;
Explanation of the difference between the two scopes of web page authorization:
1. Authorization login The web page authorization initiated with snsapi_base as the scope is used to obtain the entry page The user's openid is authorized silently and automatically jumps to the callback page. What the user perceives is that he directly enters the callback page (often a business page). Features: The user is unaware;
2. Silent authorization. Web page authorization initiated with snsapi_userinfo as the scope is used to obtain the user's basic information. However, this kind of authorization requires the user to manually agree, and since the user has agreed, there is no need to pay attention, and the user's basic information can be obtained after authorization.
Silent authorization in special scenarios:
For users who have followed the official account, if the user enters from the official account’s session or custom menu The web authorization page of this official account, even if the scope is snsapi_userinfo, is silently authorized and the user is not aware of it.
Web page authorization process:
1, guide the user to enter the authorization page to agree to the authorization, Obtain code
Ensure that the WeChat public account has the permissions of the authorization scope (scope parameter) and guide the user to the authorization page
Reference link :
scope is snsapi_base
Note: appid, redirect_uri, state must be negotiated with the backend
If the user agrees to the authorization, the page will jump to redirect_uri/?code=CODE&state=STATE.
2, exchange code for web page authorization access_token (backend operation)
redirect_uri on the url where the page jumps back. /?code=CODE&state=STATE. code
The code is exchanged for the webpage authorization access_token. If the scope of the webpage authorization is snsapi_base, in this step, while obtaining the webpage authorization access_token, the openid is also obtained, and the snsapi_base-style webpage authorization process is completed. So far.
3: Personal information is required. The background gets the value through the code and returns it to the front end for operation
The above is the detailed content of PHP implements WeChat web page login authorization development. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn