Technical Guidelines for Realizing Wechat Scan Code Login on PC

Table of contents

document

Step 1: Register on WeChat Open Platform

Step 2: Introduce the WeChat scan code login component

Step 3: Create a scan code login button

Step 4: Handle callbacks

Summarize


WeChat QR code login is a convenient authentication method that allows users to quickly log in to a website or application using their WeChat account. In this article, we will introduce the technical guidelines on how to implement WeChat scan code login on the PC side. By reading this guide, you will understand the steps and basic principles required to implement WeChat scan code login.

document

Preparation | WeChat Open Documentation WeChat Developer Platform Documentation https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html

Preparation

The website application WeChat login is a WeChat OAuth2.0 authorized login system based on the OAuth2.0 protocol standard. Before performing WeChat OAuth2.0 authorized login access, register a developer account on the WeChat open platform, and have a website application that has been approved, and obtain the corresponding AppID and AppSecret. After applying for WeChat login and passing the review, you can start to receive into the process.

Authorization Process Description

WeChat OAuth2.0 authorized login allows WeChat users to securely log in to third-party applications or websites using WeChat identities. After the WeChat user authorizes login to a third-party application that has been connected to WeChat OAuth2.0, the third party can obtain the user's interface call credentials ( access_token ) , through the access_token, the authorization relationship interface of the WeChat open platform can be called, so as to obtain the basic open information of WeChat users and help users realize basic open functions, etc. WeChat OAuth2.0 authorization login currently supports authorization_code mode, which is suitable for application authorization with server side. The overall process of this mode is:

1. 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
2. 通过code参数加上AppID和AppSecret等,通过API换取access_token;
3. 通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。

Step 1: Request CODE 

Before the third party uses the website application authorization to log in, please note that the corresponding web page authorization scope (scope=snsapi_login) has been obtained, then 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 "This link cannot be accessed", please check whether the parameters are filled 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.

parameter Is it necessary illustrate
appid yes App unique identifier
redirect_uri yes Please use urlEncode to process the link
response_type yes fill in the code
scope yes Application authorization scope, with multiple scopes separated by commas (,), web applications currently only fill in snsapi_login
state no It is used to keep the state of the request and callback, and bring it back to the third party as it is after the request is authorized. This parameter can be used to prevent csrf attacks (cross-site request forgery attacks). It is recommended that third parties bring this parameter, which can be set to a simple random number plus session for verification
lang no Interface language, supports cn (Simplified Chinese) and en (English), the default is cn

return instructions

After the user permits authorization, it will be redirected to the URL of redirect_uri with code and state parameters

redirect_uri?code=CODE&state=STATE

If the user forbids authorization, no redirection will occur.

Embed WeChat login QR code into your own page

In order to meet the more customized needs of the website, we also provide a second way to obtain the code, which supports the website to embed the WeChat login QR code into its own page, and the user uses WeChat to scan the code to authorize and return 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 having to jump to the WeChat domain to log in and then return, so as to improve the fluency and success rate of WeChat login. Implementation method of website embedded QR code WeChat login JS:

F.A.Q

  1. What is an authorized temporary ticket (code)? Answer: The third party needs to use the code to obtain the access_token. The timeout period of the code is 10 minutes. A code can only be successfully exchanged for an access_token once and then it will become invalid. The temporary nature of the code guarantees the security of WeChat authorized login. Third parties can further strengthen their own authorized login security by using https and state parameters.

  2. What is the authorization scope (scope)? Answer: The authorization scope (scope) represents the interface authority authorized by the user to the third party. After the third-party application needs to apply for the permission to use the corresponding scope from the WeChat open platform, use the method described in the document to allow the user to authorize. After the user authorizes, the obtained The interface can only be called after corresponding access_token.

Step 1: Register on WeChat Open Platform

To realize WeChat scan code login, you first need to register and obtain the application ID (AppID) and key (AppSecret) of the WeChat open platform. Create a new application on the WeChat open platform, and fill in relevant information, such as application name, website URL, etc. After completing the registration, you will get a unique AppID and AppSecret, which can be configured in the settings of the open platform.

WeChat open platform https://open.weixin.qq.com/

After opening the WeChat open platform , click Register in the upper right corner and fill in the basic information

  2. Register the main body information of the enterprise

 

 3. Confirm the subject information

 2. After successful registration, perform open authentication

1. On the homepage of the open platform, click [Account Center] -> [Developer Qualification Certification] -> [Apply Now] → [Agree Agreement]

  2. Select the type of certification (generally an enterprise) and fill in relevant information

After completing the authentication, create a website application  

 3. Website application creation

After the website system is deployed. Can create website applications to use WeChat related services

 Log in to the WeChat open platform [Management Center] —> [Website Application] —> [Create]

Step 2: Introduce the WeChat scan code login component

To implement WeChat scan code login on the PC side, you need to introduce the WeChat scan code login component into the website or application. This step can be achieved by adding a JavaScript file in the HTML page. Here is an example:

http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js

Step 3: Create a scan code login button

In the HTML page, you can add a button to trigger the WeChat scan code login process. When the user clicks the button, the WeChat scan code login interface will be called.

<div id="login_container"></div>
  //发请求获取微信扫码二维码需要参数
  //咱们在想后台的服务器发请求,获取微信扫码登录页面参数
  //还需要携带一个参数:告诉后台服务器用户授权成功以后重定向项目某一个页面
  let redirect_URL = encodeURIComponent(window.location.origin + "/wxlogin");
  let result: WXLoginResponseData = await reqWxLogin(redirect_URL);
  //生成微信扫码登录二维码页面
  //@ts-ignore
  new WxLogin({
    self_redirect: true, //true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
    id: "login_container", //显示二维码容器设置
    appid: result.data.appid, //应用位置标识appid
    scope: "snsapi_login", //当前微信扫码登录页面已经授权了
    redirect_uri: result.data.redirectUri, //填写授权回调域路径,就是用户授权成功以后,微信服务器向公司后台推送code地址
    state: result.data.state, //state就是后台服务器重定向的地址携带用户信息
    style: "black",
    href: "",
  });

In the above code, you need to replace it your_appidwith the AppID you obtained when you registered the app on the WeChat open platform, and at the same time, your_redirect_uriand your_statealso need to be replaced with your actual value.

parameter Is it necessary illustrate
self_redirect no true: the mobile phone can jump to redirect_uri in the iframe after clicking the confirmation login, false: the mobile phone can jump to the redirect_uri in the top window after clicking the confirmation login. The default is false.
id yes The third-party page displays the container id of the QR code
appid yes The unique identifier of the application, which is obtained after the application is submitted and approved by the WeChat open platform
scope yes Application authorization scope, with multiple scopes separated by commas (,), web applications currently only need to fill in snsapi_login
redirect_uri yes Redirect address, UrlEncode is required
state no It is used to keep the state of the request and callback, and bring it back to the third party as it is after the request is authorized. This parameter can be used to prevent csrf attacks (cross-site request forgery attacks). It is recommended that third parties bring this parameter, which can be set to a simple random number plus session for verification
style no "black" and "white" are available, and the default is black text description. See the FAQ at the bottom of the document for details
href no Custom style links, third parties can override the default styles according to actual needs. See the FAQ at the bottom of the document for details

Step 4: Handle callbacks

After the user scans the QR code to log in on the WeChat client, they will be redirected to the callback URL you set in step 3. In the backend code corresponding to this URL, you need to handle the callback and get the user authorization information.

By requesting the WeChat interface, the user's and other information access_tokencan be obtained , which can be used for further identity verification or to obtain user information.access_tokenopenid

Parameter Description

parameter Is it necessary illustrate
appid yes The unique identifier of the application, which is obtained after the application is submitted and approved by the WeChat open platform
secret yes The application key AppSecret is obtained after the application is submitted and approved on the WeChat open platform
code yes Fill in the code parameter obtained in the first step
grant_type yes 填authorization_code

java

// 处理回调的后端代码示例(Java)

// 获取code
String code = request.getParameter("code");

// 请求access_token接口
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=your_appid&secret=your_secret&code=" + code + "&grant_type=authorization_code";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {
    // 读取返回结果
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // 解析返回结果
    JSONObject jsonObject = new JSONObject(response.toString());
    String accessToken = jsonObject.getString("access_token");
    String openid = jsonObject.getString("openid");

    // 可以进一步进行身份验证或获取用户信息
}

return instructions

correctly returns:

parameter illustrate
access_token API call certificate
expires_in access_token interface call credential timeout, unit (second)
refresh_token User refreshes access_token
openid Authorized user unique identifier
scope User authorization scopes, separated by commas (,)
unions This field will only appear if and only if the website application has been authorized by the user's userinfo.

 Step 3: Call the interface through access_token

After obtaining the access_token, the interface call must have the following prerequisites:

1. access_token有效且未超时;
2. 微信用户已授权给第三方应用账号相应接口作用域(scope)。

For the 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
snsapi_base /sns/oauth2/refresh_token To refresh or renew access_token use
snsapi_base /sns/auth Check access_token validity
snsapi_userinfo /sns/userinfo Obtain user personal information

Among them, snsapi_base belongs to the basic interface. If the application already has other scope permissions, it has the permission of snsapi_base by default. Using snsapi_base allows mobile webpage authorization to bypass the action of jumping to the authorization login page to request user authorization, and directly jumps to a third-party webpage with an authorization temporary ticket (code), but the user's authorized scope (scope) is only snsapi_base , resulting in the inability to obtain data and basic functions that require user authorization. For interface calling methods, please refer to "WeChat Authorization Relationship Interface Calling Guide"

Summarize

By following the above steps, you can realize the WeChat scan code login function on the PC side. First, register and obtain the AppID and AppSecret of the WeChat open platform. Then, introduce the WeChat scan code login component into the HTML page, and create a scan code login button. Finally, process the callback in the backend code of the callback URL and obtain user authorization information to implement authentication or other related operations.

Implementing WeChat scan code login can provide a more convenient login experience and bring a lot of convenience to users and website administrators. Hope this article helps you!

Guess you like

Origin blog.csdn.net/qq_63358859/article/details/131826717