


Force.com WeChat enterprise account development series-enable two-step verification
Mar 03, 2017 am 09:49 AM
After WeChat launched the Enterprise Account in September, it caused quite a stir in the industry. Many companies are thinking about how the Enterprise Account will affect their operations. Starting from this article, I We will elaborate on the relevant knowledge of WeChat enterprise account development, and this article will focus on how to achieve secondary verification of a higher security mechanism.
Apply for an enterprise experience account:
As the name suggests, an enterprise account is an account that enterprises apply for. When applying, just like applying for a service account, you need to provide various organizational certification documents. It is difficult for developers to operate. Fortunately, Tencent has also opened an application for experience accounts just like service accounts. Note that the validity period of enterprise experience accounts is very short, only 90 days (service account test accounts have a validity period of 1 year), and If the enterprise experience account is not used for a long time, you will receive an early expiration reminder email from Tencent. The application link for the enterprise experience account is as follows. Developers only need to follow Tencent’s guidance to complete the registration steps and get the experience account immediately:
http://qydev.weixin.qq.com/try?t= experience
Add members to the address book:
Different from the public account, because it is for internal use of the company, Tencent allows companies to actively add fans. The specific operation is to enter After the address book, click the + button to add a new member. Note that as the only personal identification information, there must be at least one WeChat ID, mobile phone number or email address. It is usually difficult to directly collect WeChat IDs. Generally, you can use the mobile phone number and email address in the company's HR database. Information, in addition to manual addition, you can also add it through Excel template import and Tencent Enterprise Account WeChat API. The API to add users will be introduced in a later chapter.
##After the input is completed, the QR code of the enterprise WeChat ID can be sent to the employee. After the employee scans it, the system's default enterprise ID assistant will automatically appear. The assistant will automatically guide the employee through the mailbox or The mobile phone verification code is used to complete the process of employee identity binding. This is a one-time verification. The company ensures the accuracy of the employee data in the address book by itself. Subsequently, it relies on Tencent for employee verification. After the verification is passed, the question mark in the address book status column will disappear. Indicates that one verification is passed:
For this we can refer to the official interface document of Enterprise Account http://qydev.weixin.qq.com/wiki/index.phptitle=%E5%85%B3%E6%B3%A8% E4%B8%8E%E5%8F%96%E6%B6%88%E5%85%B3%E6%B3%A8 develops corresponding pages on the Force.com platform. Develop a page for secondary verification: Similarly, the page is divided into two parts, one part is the display part, which is used to enter the user name and password. The page diagram is as follows. User Enter the username user and password 123 and click the bind button to complete the binding:
For this we can refer to the official interface document of the Enterprise Account http://qydev.weixin.qq.com/wiki/index.phptitle=%E5 %85%B3%E6%B3%A8%E4%B8%8E%E5%8F%96%E6%B6%88%E5%85%B3%E6%B3%A8 develop corresponding pages on the Force.com platform.
Develop a page for secondary verification:
Similarly, the page is divided into two parts. One part is the display part, which is used to enter the user name and password. The page diagram is as follows. The user enters the user name user and password 123 and clicks the bind button to complete the binding:
The page name is EmployeeAuth, the page code is as follows, some tags are unique to apex code , no in-depth understanding is required, the important thing is that the action attribute of the button in line 13 specifies the bind method. When the button is clicked, the bind method of the controller class EmployeeAuthController will be called:
<apex:page standardstylesheets="false" showHeader="false" sidebar="false" controller="EmployeeAuthController"> <font size="50"> <h1>Please input your user name and password</h1> </font> <font size="30"> UserName: user<br /> Password: 123<br /><br /> <hr/> <apex:form > UserName: <apex:inputText size="100" style="height:100px" value="{!strUsername}" id="strUsername"/><br /><br /> Password: <apex:inputText size="100" style="height:100px" value="{!strPassword}" id="strPassword"/><br /><br /> <center> <apex:commandButton value="Bind" style="width:600px; height:100px;font-size:50px" action="{!bind}" id="bind" /> </center> </apex:form> {!msg} </font> </apex:page>
Before interpreting the code of the EmployeeAuthController controller class, let’s first look at the steps of WeChat secondary authentication.
Steps and mechanism of secondary verification:
1. First, when WeChat first verification (or email or mobile phone number verification) is completed, WeChat will send a message as shown below to the user:
2. Page jump:
When the user clicks on this image and text, it actually opens a The webpage located under the open.weixin.qq.com website. This page will do some processing and then jump to the URL set previously in the second verification, which is the page we are developing. When it jumps, it will jump to us. Add the parameter code=CODE&state=STATE after the set URL. For example, in this example, the URL configured for the second verification is http://johnson0001-developer-edition.ap1.force.com/EmployeeAuth, then start from Tencent openweixin.qq. The URL actually opened after com jumps is http://johnson0001-developer-edition.ap1.force.com/EmployeeAuth?code=CODE&state=STATE. Tencent did not explain what the state parameter here is for, and it is not important at the moment. The important thing is the code parameter. You can use this parameter to call Tencent's oauth2 interface in exchange for the employee's userid. Note that userid is a very important concept. There is no WeChat OpenId in the enterprise account. Only userid is used to uniquely identify the user. This userid actually Above is the account field value when we maintain the address book:
##3. Call the Tencent oauth2 interface through code to exchange for the employee useridFor instructions on this interface, please refer to the Tencent documentation http://qydev.weixin.qq.com/wiki/ index.phptitle=%E6%A0%B9%E6%8D%AEcode%E8%8E%B7%E5%8F%96%E6%88%90%E5%91%98%E4%BF%A1%E6%81 %AF, you can also participate in the instructions below. What needs special explanation here is the access token and agentid:
## Readers who have done WeChat public account development or have read the previous related development articles should be familiar with it. When actively calling Tencent’s API, access token is required to ensure the legitimacy of the access. , there is also a special interface for obtaining access tokens. For detailed introduction, please refer to Tencent company documents http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%BB%E5%8A %A8%E8%B0%83%E7%94%A8. To put it simply, obtaining the access token is actually through the following interface:
https://qyapi.weixin.qq.com/cgi-bin/gettoken ?corpid=id&corpsecret=secrect
Corpid is easy to find in this interface. You can find it by opening the settings, as shown below:
不過(guò)corpsecret就沒(méi)那么好找,實(shí)際是需要系統(tǒng)管理員在后臺(tái)創(chuàng)建管理組,創(chuàng)建管理組后就可以擁有相應(yīng)的Secret,而這個(gè)Secret所擁有的訪問(wèn)權(quán)限就是系統(tǒng)管理員創(chuàng)建的管理組所擁有的權(quán)限,騰訊文章http://qydev.weixin.qq.com/wiki/index.php?title=Secret也有提到:
再回過(guò)頭來(lái)說(shuō)agentid騰訊文檔里提到指的是“跳轉(zhuǎn)鏈接時(shí)所在的企業(yè)應(yīng)用ID”,在本例里其實(shí)指的就是發(fā)送“身份驗(yàn)證”圖文消息的那個(gè)應(yīng)用也就是“企業(yè)小助手”的應(yīng)用ID,當(dāng)然在不同的用戶場(chǎng)景里可能會(huì)是不同的應(yīng)用在調(diào)用換取userid接口,如何查看“企業(yè)小助手”的應(yīng)用ID呢?進(jìn)到應(yīng)用中心,第一個(gè)就是企業(yè)小助手,點(diǎn)擊進(jìn)入就可以看到如下圖所示的企業(yè)應(yīng)用ID了:
4. 二次驗(yàn)證
拿到userid后實(shí)際就可以進(jìn)行二次驗(yàn)證了,二次驗(yàn)證的方式有很多種,例如如果公司已經(jīng)建立起良好的通訊錄管理機(jī)制(userid等和企業(yè)人力資源數(shù)據(jù)庫(kù)同步,入職離職員工均能和企業(yè)號(hào)通訊錄同步),拿到userid后只要判斷這個(gè)userid是一位在職員工就可以自動(dòng)判斷為二次驗(yàn)證通過(guò),或者再保險(xiǎn)點(diǎn)如本例演示的,要求員工輸入公司的員工用戶名和密碼進(jìn)行驗(yàn)證。留意,輸入用戶名和密碼驗(yàn)證的頁(yè)面也就是我們前面提到的二次驗(yàn)證頁(yè)面是屬于企業(yè)擁有也是企業(yè)開發(fā)的,這樣就確保了企業(yè)對(duì)安全的控制,具體操作上,用戶輸入用戶名和密碼后企業(yè)可以調(diào)用已有的接口進(jìn)行驗(yàn)證,如果驗(yàn)證成功則將員工的userid等信息保存在業(yè)務(wù)系統(tǒng)數(shù)據(jù)庫(kù)中一遍后續(xù)操作。
5.通知騰訊關(guān)注成功
現(xiàn)在最后一步等企業(yè)在自己的網(wǎng)頁(yè)里完成了用戶驗(yàn)證后只剩下通知騰訊該用戶已經(jīng)驗(yàn)證成功讓相應(yīng)員工關(guān)注成功,此時(shí)應(yīng)該調(diào)用如下接口,可以看到接口需要的第二個(gè)參數(shù)即是我們前面換回來(lái)的userid:
https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?access_token=ACCESS_TOKEN&userid=USERID
此接口的詳細(xì)說(shuō)明如下:
二次驗(yàn)證的代碼實(shí)現(xiàn):
按照前面的思路,我們首先獲取從騰訊跳轉(zhuǎn)過(guò)來(lái)的code,并通過(guò)code換取用戶的userid,換取的這個(gè)過(guò)程在頁(yè)面加載中完成,為此主要代碼應(yīng)放在類構(gòu)造器里。下面的代碼里設(shè)置了五個(gè)變量,其中strPassword和strUsername和用戶在頁(yè)面里輸入的用戶名和密碼相對(duì)應(yīng),userID用來(lái)存儲(chǔ)換回來(lái)的userid信息,msg用來(lái)調(diào)試幫助在頁(yè)面里顯示中間信息,accessToken則用來(lái)存儲(chǔ)access token:
public class EmployeeAuthController { public String strPassword { get; set; } public String strUsername { get; set; } public String msg { get; set; } public String userID { get; set; } public String accessToken { get; set; } public EmployeeAuthController (){ accessToken = obtainAccessToken(); String code = ApexPages.currentPage().getParameters().get('code'); //Obtain user ID Http h = new Http(); HttpRequest req = new HttpRequest(); req.setMethod('GET'); req.setHeader('Accept-Encoding','gzip,deflate'); req.setHeader('Content-Type','text/xml;charset=UTF-8'); req.setHeader('User-Agent','Jakarta Commons-HttpClient/3.1'); req.setEndpoint('https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=' + accessToken + '&code=' + code + '&agentid=0'); String bodyRes = ''; try{ HttpResponse res = h.send(req); bodyRes = res.getBody(); } catch(System.CalloutException e) { System.debug('Callout error: '+ e); ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage())); } msg = bodyRes ; //String operation to obtain userID: JSONParser parser = JSON.createParser(bodyRes); while(parser.nextToken() != null){ if((parser.getCurrentToken() == JSONToken.FIELD_NAME)){ String fieldName = parser.getText(); parser.nextToken(); if(fieldName == 'UserId'){ userID = parser.getText(); } } } msg = userID; } }
上述代碼第9行調(diào)用obtainAccessToken方法獲取accessToken,后續(xù)會(huì)介紹該方法的詳情,accessToken兩個(gè)小時(shí)內(nèi)會(huì)失效,所以這里采取實(shí)時(shí)獲取的方式,當(dāng)然可以設(shè)計(jì)的再巧妙些以省卻每次實(shí)時(shí)獲取accessToken的網(wǎng)絡(luò)開銷。第10行獲得了從騰訊跳轉(zhuǎn)過(guò)來(lái)時(shí)帶的code參數(shù),從第11行通過(guò)HttpRequest方法來(lái)調(diào)用換取接口獲得userid,留意第18行指定了agentid為0,這是因?yàn)轵?yàn)證消息是從企業(yè)小助手應(yīng)用發(fā)起的,而企業(yè)小助手應(yīng)用id是0。第29行開始解析返回來(lái)的JSON數(shù)據(jù)獲取userid。
下面是obtainAccessToken方法,方法內(nèi)容也比較直接,主要通過(guò)調(diào)用gettoken接口來(lái)獲取accessToken,并通過(guò)JSONParser類來(lái)解析返回的JSON數(shù)據(jù)以獲得accessToken:
private String obtainAccessToken(){ String token; Http h = new Http(); HttpRequest req = new HttpRequest(); req.setMethod('GET'); req.setHeader('Accept-Encoding','gzip,deflate'); req.setHeader('Content-Type','text/xml;charset=UTF-8'); req.setHeader('User-Agent','Jakarta Commons-HttpClient/3.1'); req.setEndpoint('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx548178d7f347f582&corpsecret=9pwWy0AVoT6V65hnwZLYdi4jnLLx65ofBRb_Ds0mAozysQoywDaqbqYCqglm2vhr'); String bodyRes = ''; try{ HttpResponse res = h.send(req); bodyRes = res.getBody(); } catch(System.CalloutException e) { System.debug('Callout error: '+ e); ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage())); } msg = bodyRes; JSONParser parser = JSON.createParser(bodyRes); while(parser.nextToken() != null){ if((parser.getCurrentToken() == JSONToken.FIELD_NAME)){ String fieldName = parser.getText(); parser.nextToken(); if(fieldName == 'access_token'){ token= parser.getText(); } } } msg = token; return token; }
接下來(lái)最重要的方法是bind方法,該方法將負(fù)責(zé)用戶身份驗(yàn)證以及通知騰訊用戶關(guān)注成功,可以看到下面代碼里第2行到第6行只做了很簡(jiǎn)單的用戶名密碼校驗(yàn),真實(shí)場(chǎng)景里可以根據(jù)企業(yè)的具體認(rèn)證機(jī)制進(jìn)行替換,從第9行開始也即企業(yè)內(nèi)部用戶認(rèn)證通過(guò)后開始調(diào)用authsucc接口通知騰訊用戶關(guān)注成功。
public PageReference bind() { if(!strUsername.equals('user')){ msg = 'Please input correct user name'; } else if(!strPassword.equals('123')){ msg = 'Please input correct password'; } else{ msg = 'Bind successfully!'; //Notify tencent to add user Http h = new Http(); HttpRequest req = new HttpRequest(); req.setMethod('GET'); req.setHeader('Accept-Encoding','gzip,deflate'); req.setHeader('Content-Type','text/xml;charset=UTF-8'); req.setHeader('User-Agent','Jakarta Commons-HttpClient/3.1'); req.setEndpoint('https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?access_token=' + accessToken + '&userid=' + userID); String bodyRes = ''; try{ HttpResponse res = h.send(req); bodyRes = res.getBody(); } catch(System.CalloutException e) { System.debug('Callout error: '+ e); ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage())); } msg = bodyRes ; } }
?更多Force.com微信企業(yè)號(hào)開發(fā)系列- 啟用二次驗(yàn)證相關(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)
