


OAuth is an open protocol that allows users to let third-party applications obtain the user's private resources (such as user personal information, photos, videos, contact lists) stored on a website in a secure and standard manner without requiring Provide username and password to third-party applications. This article will introduce in detail the OAuth protocol and its specific implementation in WeChat.
OAuth2.0 protocol introduction
OAuth2.0 is the next version of the OAuth protocol, but it is not backward compatible with OAuth 1.0. OAuth 2.0 focuses on simplicity for client developers, while providing specialized authentication flows for web applications, desktop applications and mobile, and living room devices. OAuth 2.0 allows users to provide a token instead of a username and password to access their data stored with a specific service provider. Each token authorizes a specific website (for example, a video editing website) to access a specific resource (for example, just the videos in a certain album) within a specific period of time (for example, within the next 2 hours). In this way, OAuth allows users to authorize third-party websites to access their information stored on another service provider without sharing their access permissions or the entire contents of their data.
The specific process of OAuth2.0 authentication and authorization:
The three parties involved in the process of Oauth2.0 authentication and authorization include:
1 . Service provider, which users use to store protected resources such as photos, videos, and contact lists.
2. User, the owner of protected resources stored on the service provider.
3. Client, a third-party application that wants to access the service provider's resources, usually a website, such as a website that provides photo printing services. Before the authentication process, the client must apply for a client identity from the service provider.
The process of using OAuth for authentication and authorization is as follows:
1. The user accesses the client's website and wants to operate the user's resources stored on the service provider;
2. The client requests a temporary token from the service provider;
3. After the service provider verifies the client's identity, it grants a temporary token;
4. After the client obtains the temporary token, it directs the user to the service provider's authorization page to request user authorization. In this process, the temporary token and the client's callback connection are sent to the service provider;
5. The user enters the username and password on the service provider's web page, and then authorizes the client to access the requested resource. ;
6. After the authorization is successful, the service provider guides the user to return to the client's web page;
7. The client obtains the access token from the service provider based on the temporary token;
8. The service provider grants the client an access token based on the temporary token and the user's authorization;
9. The client uses the obtained access token to access protected files stored on the service provider. H.
WeChat webpage OAuth2.0 authorization:
If the user accesses the third-party webpage of the official account in WeChat (except Web WeChat), the official account developer can obtain the current Basic user information (including nickname, gender, city, country). Using user information, you can realize functions such as experience optimization, user source statistics, account binding, and user identity authentication.
It should be noted that the interface for obtaining basic user information (which will be introduced in the blog post later) can only obtain the user's basic information based on the user's OpenID when the user interacts with the public account, and the user's basic information can be obtained through web page authorization. For the user's basic information, there is no need for message interaction. As long as the user enters the official account's webpage, an interface requesting user authorization will pop up. After the user authorizes it, his or her basic information can be obtained (this process does not even require the user to have followed the official account.)
Below we will show the detailed development process through a specific example.
Configure the authorization callback domain name:
Before the WeChat official account requests user webpage authorization, the developer needs to first Configure the authorization callback name on the My Service page of the public platform website. It should be noted that the domain name here does not include http:// or https://. In addition, the authorization callback domain name configuration specification is the full domain name. For example, the domain name that requires web page authorization is: www.qq.com. After configuration, all pages under this domain name, such as http://www.qq.com/music.html, http: //www.qq.com/login.html can perform OAuth2.0 authentication. However, http://pay.qq.com and http://music.qq.com cannot perform OAuth2.0 authentication.
To this end, enter the service page (use the official service account or certified subscription account and find it through my service. If it is a test account, you can find it directly on the homepage) and find the OAuth2.0 web page authorization. Click the modify link on the right:
Enter the domain name in the pop-up window and click the OK button to save:
User Agree to authorize and obtain Code:
This step is equivalent to the second step of the OAuth2.0 authentication process introduced earlier "The client requests a temporary token from the service provider". The Code here is the temporary token. For this purpose, you can request WeChat's OAuth2 .0 interface to obtain the Code. A callback page URL needs to be specified in the parameters of this interface. For this we need to create an Apex Page. For this purpose, log in to Force.com and find the domain name. The domain name usually accessed from China is https:// ap1.salesforce.com, enter https://ap1.salesforce.com/apex/oauth2test in the browser address bar, Force.com will prompt that the page does not exist, click the "Create Page oauth2test" link to create the page:
The created page is as follows. If the developer mode is enabled, the page is divided into upper and lower parts. The upper part is the display effect, and the lower part is the source code editing window. By default Force.com will apply its own top navigation, left navigation, and CSS styles to the newly created page:
We tell Force by adding the following code to the first line .com do not use the default CSS style, do not display the top and left navigation bars, and the last controller attribute specifies the controller class corresponding to the apex page, similar to the aspx.cs class corresponding to the aspx page, and the mouse remains in the edit bar window, hold down the Ctrl + S key combination to save the edited code:
At this time, the corresponding oauth2testcontroller class does not exist, and the browser will report the following error:
Click here The two links "Create Apex class 'public class oauth2testcontroller'" automatically create the controller class. Note that the only difference between these two links is the "with sharing" keyword. This keyword specifies that the current class has the same access rights to various objects (equivalent to data tables), fields, etc. as the currently logged in user. If not specified, Apex The page will have access to all objects and fields. After creation, there will be an additional controller class Tab in the code editing bar below:
Add the code in this class as follows:
public class oauth2testcontroller { public String code {get; set;} public oauth2testcontroller(){ code = ApexPages.currentPage().getParameters().get('code'); if(String.isBlank(code)){ code = 'No Code'; } } }
The 2nd line of this code defines a public attribute code. The 4th line obtains the code parameter in the URL through the ApexPages object, and then determines whether the code value is empty. If it is empty, it will prompt No. Code. Below we will see that when WeChat authorization successfully calls back this URL, the code parameter will be added to the URL.
Next, slightly modify the front page and display the obtained code value on the page:
<apex:page standardstylesheets="false" showHeader="false" sidebar="false" controller="oauth2testcontroller"> {!code} </apex:page>
{!Object name} is the syntax used to display object values ??in the Force.com Visualforce page, then Next, we need to configure the page to be accessible through the public network. To do this, after logging in to Force.com, enter Setup –> Develop –> Sites, and click on the Site Label corresponding to the site as shown below:
After entering the detailed configuration page, find "Site Visualforce Page" and click the Edit button on the right:
Find the oauth2test page in the left list and add it Go to the right and save the changes:
You can now access it through the http://johnson0001-developer-edition.ap1.force.com/oauth2test public network address The page created earlier. Next, we can use the OAuth2 authentication interface of the WeChat platform to compose the URL and guide users to access it through WeChat. The format of the interface is as follows:
https://open.weixin.qq.com/connect/oauth2/ authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
若提示“該鏈接無法訪問”,請(qǐng)檢查參數(shù)是否填寫錯(cuò)誤,是否擁有scope參數(shù)對(duì)應(yīng)的授權(quán)作用域權(quán)限,其中每個(gè)參數(shù)的詳細(xì)說明如下:
在我們的例子里URL如下,其中scope我們指定為snsapi_userinfo,彈出授權(quán)頁面:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3b3aef2c09447269&redirect_uri=http://johnson0001-developer-edition.ap1.force.com/oauth2test&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
興許是測試賬號(hào)的關(guān)系,雖然微信接口文檔里提到在制定scope為snsapi_userinfo的情況下會(huì)彈出如下圖左所示的授權(quán)頁面,但反復(fù)嘗試(乃至刪除并重新關(guān)注賬號(hào))中也沒有看到該頁面,不過重點(diǎn)是我們得到了臨時(shí)令牌,如下圖右所示。右圖實(shí)際是http://johnson0001-developer-edition.ap1.force.com/oauth2test頁面,用戶同意授權(quán)后跳轉(zhuǎn)到(或者我遇到的實(shí)際情況是直接跳轉(zhuǎn))到redirect_uri/?CODE&state=STATE。若用戶禁止授權(quán),則重定向后不會(huì)帶上code參數(shù),僅會(huì)帶上state參數(shù)redirect_uri?state=STATE。
另外特別需要說明的是,code作為換取access_token的臨時(shí)票據(jù),每次用戶授權(quán)帶上的code都不一樣,code只能使用一次,5分鐘未被使用自動(dòng)過期。
通過Code換取網(wǎng)頁授權(quán)access_token:
首先請(qǐng)注意,這里通過code換取的網(wǎng)頁授權(quán)access_token,與基礎(chǔ)支持中的access_token不同。公眾號(hào)可通過下述接口來獲取網(wǎng)頁授權(quán)access_token。如果網(wǎng)頁授權(quán)的作用域?yàn)閟nsapi_base,則本步驟中獲取到網(wǎng)頁授權(quán)access_token的同時(shí),也獲取到了 openid,snsapi_base式的網(wǎng)頁授權(quán)流程即到此為止。 獲取code后,可以通過以下接口獲取access_token:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
這里的CODE即為通過前面方式獲得的臨時(shí)令牌(票據(jù)),參數(shù)的具體說明如下:
將URL直接輸入到瀏覽器地址欄即可得到返回?cái)?shù)據(jù),當(dāng)然真實(shí)場景里更多通過后臺(tái)代碼來請(qǐng)求,正確返回時(shí)的JSON數(shù)據(jù)包如下:
{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
參數(shù)的具體說明如下:
錯(cuò)誤時(shí)微信會(huì)返回JSON數(shù)據(jù)包如下(示例為Code無效錯(cuò)誤):
{"errcode":40029,"errmsg":"invalid code"}
在本例中獲得的access_token實(shí)例如下:
{"access_token":"OezXcEiiBSKSxW0eoylIeMEUA_AZuBDY8AO0IIw270MMsvemqLvgx1HqemeXIZfzXW2d6yHCPy9cA1yHZ1jHCkwlH5Ct5Jfa1jOQm88M9LzU_O8BCKMNhN7yLlHJfOFLuf4lLTNGOOsoWYxQzYVNGw","expires_in":7200,"refresh_token":"OezXcEiiBSKSxW0eoylIeMEUA_AZuBDY8AO0IIw270MMsvemqLvgx1HqemeXIZfz_Vj5pJZlv2V5wK9EzWmxQmM07cqIAwMXOdqzlQs-NY4hiyENP4WhO4Twpko-3iY_pAPZRnGGmAVt3DirZaWIyg","openid":"ou-37t936RNZEcW0mI75RN2pdxkc","scope":"snsapi_userinfo"}
可以看到上面access_token的默認(rèn)失效時(shí)間是7200秒,也就是2小時(shí),當(dāng)access_token超時(shí)后,可以通過refresh_token進(jìn)行刷新,refresh_token擁有較長的有效期(7天、30天、60天、90天),當(dāng)refresh_token失效后,需要用戶重新授權(quán),簡化理解起見,我們?cè)诒疚牡淖詈笤俳榻B相關(guān)技術(shù)。
拉取用戶信息(需Scope為snasapi_userinfo):
通過access_token獲取用戶信息的接口如下,使用GET方法:
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
參數(shù)具體說明如下:
本例的URL如下:
https://api.weixin.qq.com/sns/userinfo?access_token=OezXcEiiBSKSxW0eoylIeMEUA_AZuBDY8AO0IIw270MMsvemqLvgx1HqemeXIZfzXW2d6yHCPy9cA1yHZ1jHCkwlH5Ct5Jfa1jOQm88M9LzU_O8BCKMNhN7yLlHJfOFLuf4lLTNGOOsoWYxQzYVNGw&openid=ou-37t936RNZEcW0mI75RN2pdxkc&lang=zh_CN
輸入瀏覽器訪問即可得到相應(yīng)的用戶信息:
{"openid":"ou-37t936RNZEcW0mI75RN2pdxkc","nickname":"王浩","sex":1,"language":"zh_CN","city":"松江","province":"上海","country":"中國","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/lqsZNvDqcXe8nBKHBPsp9YHuZXPtkzOD1uq3r3xxDicuDLKGlicNd1b371ODnn9xNBB9y9ChBSfL7tuX6m9FS8koY9Ex1iaJRDI\/0","privilege":[]}
刷新access_token:
可以通過前面在“通過Code換取網(wǎng)頁授權(quán)access_token”小節(jié)中獲得的refresh_token來調(diào)用刷新Token接口獲取更新的access_token,微信在API文檔里介紹refresh_token擁有較長的有效期(7天、30天、60天、90天),但實(shí)際微信的refresh_token的有效期是多長沒有具體說明,如果有具體經(jīng)驗(yàn)的朋友歡迎分享。微信刷新access_token的接口如下:
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
接口的具體參數(shù)定義如下:
正確時(shí)返回的JSON數(shù)據(jù)包如下:
{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
數(shù)據(jù)包的具體定義如下:
錯(cuò)誤時(shí)微信會(huì)返回JSON數(shù)據(jù)包如下(示例為Code無效錯(cuò)誤):
{"errcode":40029,"errmsg":"invalid code"}
更多Force.com WeChat development series OAuth2.0 web authorization相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
