Home > WeChat Applet > WeChat Development > Force.com WeChat enterprise account development series-enable two-step verification

Force.com WeChat enterprise account development series-enable two-step verification

高洛峰
Release: 2017-03-03 09:49:05
Original
2985 people have browsed it

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.


Force.com微信企业号开发系列- 启用二次验证Force.com微信企业号开发系列- 启用二次验证

##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:

Force.com微信企业号开发系列- 启用二次验证

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:


Force.com微信企业号开发系列- 启用二次验证

##The following window will pop up and you need to enter the company’s secondary verification page address:

Force.com微信企业号开发系列- 启用二次验证

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:


Force.com微信企业号开发系列- 启用二次验证

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>
Copy after login

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:

Force.com微信企业号开发系列- 启用二次验证

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:


Force.com微信企业号开发系列- 启用二次验证

##3. Call the Tencent oauth2 interface through code to exchange for the employee userid

For 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:


Force.com微信企业号开发系列- 启用二次验证

## 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:


Force.com微信企业号开发系列- 启用二次验证

不过corpsecret就没那么好找,实际是需要系统管理员在后台创建管理组,创建管理组后就可以拥有相应的Secret,而这个Secret所拥有的访问权限就是系统管理员创建的管理组所拥有的权限,腾讯文章http://qydev.weixin.qq.com/wiki/index.php?title=Secret也有提到:

Force.com微信企业号开发系列- 启用二次验证

再回过头来说agentid腾讯文档里提到指的是“跳转链接时所在的企业应用ID”,在本例里其实指的就是发送“身份验证”图文消息的那个应用也就是“企业小助手”的应用ID,当然在不同的用户场景里可能会是不同的应用在调用换取userid接口,如何查看“企业小助手”的应用ID呢?进到应用中心,第一个就是企业小助手,点击进入就可以看到如下图所示的企业应用ID了:

Force.com微信企业号开发系列- 启用二次验证

4. 二次验证

拿到userid后实际就可以进行二次验证了,二次验证的方式有很多种,例如如果公司已经建立起良好的通讯录管理机制(userid等和企业人力资源数据库同步,入职离职员工均能和企业号通讯录同步),拿到userid后只要判断这个userid是一位在职员工就可以自动判断为二次验证通过,或者再保险点如本例演示的,要求员工输入公司的员工用户名和密码进行验证。留意,输入用户名和密码验证的页面也就是我们前面提到的二次验证页面是属于企业拥有也是企业开发的,这样就确保了企业对安全的控制,具体操作上,用户输入用户名和密码后企业可以调用已有的接口进行验证,如果验证成功则将员工的userid等信息保存在业务系统数据库中一遍后续操作。

5.通知腾讯关注成功

现在最后一步等企业在自己的网页里完成了用户验证后只剩下通知腾讯该用户已经验证成功让相应员工关注成功,此时应该调用如下接口,可以看到接口需要的第二个参数即是我们前面换回来的userid:

https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?access_token=ACCESS_TOKEN&userid=USERID

此接口的详细说明如下:


Force.com微信企业号开发系列- 启用二次验证

二次验证的代码实现:

按照前面的思路,我们首先获取从腾讯跳转过来的code,并通过code换取用户的userid,换取的这个过程在页面加载中完成,为此主要代码应放在类构造器里。下面的代码里设置了五个变量,其中strPassword和strUsername和用户在页面里输入的用户名和密码相对应,userID用来存储换回来的userid信息,msg用来调试帮助在页面里显示中间信息,accessToken则用来存储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(&#39;code&#39;); 
        //Obtain user ID 
         Http h = new Http(); 
         HttpRequest req = new HttpRequest(); 
         req.setMethod(&#39;GET&#39;); 
         req.setHeader(&#39;Accept-Encoding&#39;,&#39;gzip,deflate&#39;); 
         req.setHeader(&#39;Content-Type&#39;,&#39;text/xml;charset=UTF-8&#39;); 
         req.setHeader(&#39;User-Agent&#39;,&#39;Jakarta Commons-HttpClient/3.1&#39;);  
         req.setEndpoint(&#39;https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=&#39; + accessToken + &#39;&code=&#39; + code + &#39;&agentid=0&#39;); 
         String bodyRes = &#39;&#39;; 
         try{ 
            HttpResponse res = h.send(req); 
            bodyRes = res.getBody(); 
         } 
         catch(System.CalloutException e) { 
            System.debug(&#39;Callout error: &#39;+ 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 == &#39;UserId&#39;){ 
                     userID = parser.getText(); 
                 } 
             } 
         } 
         msg = userID; 
    }

}
Copy after login

上述代码第9行调用obtainAccessToken方法获取accessToken,后续会介绍该方法的详情,accessToken两个小时内会失效,所以这里采取实时获取的方式,当然可以设计的再巧妙些以省却每次实时获取accessToken的网络开销。第10行获得了从腾讯跳转过来时带的code参数,从第11行通过HttpRequest方法来调用换取接口获得userid,留意第18行指定了agentid为0,这是因为验证消息是从企业小助手应用发起的,而企业小助手应用id是0。第29行开始解析返回来的JSON数据获取userid。

下面是obtainAccessToken方法,方法内容也比较直接,主要通过调用gettoken接口来获取accessToken,并通过JSONParser类来解析返回的JSON数据以获得accessToken:

 private String obtainAccessToken(){ 
        String token; 
         Http h = new Http(); 
         HttpRequest req = new HttpRequest(); 
         req.setMethod(&#39;GET&#39;); 
         req.setHeader(&#39;Accept-Encoding&#39;,&#39;gzip,deflate&#39;); 
         req.setHeader(&#39;Content-Type&#39;,&#39;text/xml;charset=UTF-8&#39;); 
         req.setHeader(&#39;User-Agent&#39;,&#39;Jakarta Commons-HttpClient/3.1&#39;); 
         req.setEndpoint(&#39;https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx548178d7f347f582&corpsecret=9pwWy0AVoT6V65hnwZLYdi4jnLLx65ofBRb_Ds0mAozysQoywDaqbqYCqglm2vhr&#39;); 
         String bodyRes = &#39;&#39;; 
         try{ 
            HttpResponse res = h.send(req); 
            bodyRes = res.getBody(); 
         } 
         catch(System.CalloutException e) { 
            System.debug(&#39;Callout error: &#39;+ 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 == &#39;access_token&#39;){ 
                     token= parser.getText(); 
                 } 
             } 
         } 
         msg = token; 
         return token; 
    }
Copy after login

接下来最重要的方法是bind方法,该方法将负责用户身份验证以及通知腾讯用户关注成功,可以看到下面代码里第2行到第6行只做了很简单的用户名密码校验,真实场景里可以根据企业的具体认证机制进行替换,从第9行开始也即企业内部用户认证通过后开始调用authsucc接口通知腾讯用户关注成功。

 public PageReference bind() {  
        if(!strUsername.equals(&#39;user&#39;)){ 
            msg = &#39;Please input correct user name&#39;;  
        } 
        else if(!strPassword.equals(&#39;123&#39;)){ 
            msg = &#39;Please input correct password&#39;;  
        } 
        else{ 
            msg = &#39;Bind successfully!&#39;; 
            //Notify tencent to add user 
            Http h = new Http(); 
            HttpRequest req = new HttpRequest(); 
            req.setMethod(&#39;GET&#39;); 
            req.setHeader(&#39;Accept-Encoding&#39;,&#39;gzip,deflate&#39;); 
            req.setHeader(&#39;Content-Type&#39;,&#39;text/xml;charset=UTF-8&#39;); 
            req.setHeader(&#39;User-Agent&#39;,&#39;Jakarta Commons-HttpClient/3.1&#39;); 
            req.setEndpoint(&#39;https://qyapi.weixin.qq.com/cgi-bin/user/authsucc?access_token=&#39; + accessToken + &#39;&userid=&#39; + userID); 
            String bodyRes = &#39;&#39;; 
             try{ 
                HttpResponse res = h.send(req); 
                bodyRes = res.getBody(); 
             } 
             catch(System.CalloutException e) { 
                System.debug(&#39;Callout error: &#39;+ e); 
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage())); 
             }    
             msg = bodyRes ;  
               } 
    }
Copy after login

 更多Force.com微信企业号开发系列- 启用二次验证相关文章请关注PHP中文网!

 

source:php.cn
Statement of this 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template