Enterprise WeChat calls the scan interface

1. Create a new application on the workbench of WeChat Work. Open App Management.

Click Modify to set the webpage to open the app (the project to which the webpage belongs needs to be deployed to the server, and the url address should be the address of the test server or the official server)

2. Click on the position in the red box as shown in the figure to enable webpage authorization and JS-SDK (the icon has already been enabled)

3. The trusted domain name is the domain name resolved from the url address of the jump page of the current application (ask the back-end classmates to analyze it). Then send the domain name to the administrator to apply for filing and verification of domain name ownership (the company’s enterprise WeChat to find the leader. The leader has administrator authority), as shown in Figure 3-2, as explained in the official document. Then click Apply to verify the domain name

Figure 3-1

 

Figure 3-2 

 Follow the prompts, download the key file first, and place the file at the same level as the code entry file (the code deployed by the back-end students to the server may not be the same as the front-end entry file, you can send the file to the back-end classmate and ask him to put it at the same level as the entry file), after putting it away, test whether it is accessible, visit the domain name address + file name (Figure 3-4), check the last item if it is accessible, and click OK.

Figure 3-3

Figure 3-4

 If verified, the activation is successful:

 4. Follow the official documentation of JS-SDK (if it is a lower version of Enterprise WeChat, change the version number of the js file to 1.0.0)

Official Documentation: Instructions for Use - Interface Documentation - Enterprise WeChat Developer Center (qq.com) icon-default.png?t=M1L8https://developer.work.weixin.qq.com/document/path/90514

4.1 Import JS files:

Introduce the following JS file on the page that needs to call the JS interface (support https): http://res.wx.qq.com/open/js/jweixin-1.2.0.js

<script src="//res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

4.2 Inject permission verification configuration through config interface

wx.config({
    beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,企业微信的corpID
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名,见 附录-JS-SDK使用权限签名算法
    jsApiList: [] // 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
});

These required parameters need to be obtained from the backend interface, and the appId is obtained from the administrator (it is unique)

Algorithm for generating signature: (It can be processed in the backend, or you can let the backend return jsapi_ticket, timestamp and nonceStr to generate the signature according to the algorithm) It is recommended that the backend handle it and directly generate the signature and return these parameters to the frontend.

JS-SDK uses permission signature algorithm - Interface document - Enterprise WeChat Developer Center (qq.com) icon-default.png?t=M1L8https://developer.work.weixin.qq.com/document/path/90506  4.3 Process successful verification through the ready interface

wx.ready(function(){
    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});

4.4 Handle failed verification through the error interface

wx.error(function(res){
    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});

 4.5 There will also be a pop-up window when the call is successful

There is a hint at the bottom of the official document:

The above functions all have a parameter, the type is object, in addition to the data returned by each interface itself, there is also a general attribute err_msg, and its value format is as follows:

  1. When the call is successful: "xxx:ok", where xxx is the name of the called interface
  2. When the user cancels: "xxx:cancel", where xxx is the name of the called interface
  3. When the call fails: its value is the specific error message

 That is to say, both success and failure of the call will return an err_msg attribute, which will pop up as a pop-up window on the mobile phone, so you can set the debug in config to false after ensuring the call is successful.

5. Call the scanning interface of the enterprise WeChat, and operate according to the official document:

Scan WeChat Work - Interface Documentation - WeChat Developer Center (qq.com) icon-default.png?t=M1L8https://developer.work.weixin.qq.com/document/path/90492 Just use the interface code directly:

wx.scanQRCode({
    desc: 'scanQRCode desc',
    needResult: 0, // 默认为0,扫描结果由企业微信处理,1则直接返回扫描结果,
    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码(一维码),默认二者都有
    success: function(res) {
        // 回调
		var result = res.resultStr;//当needResult为1时返回处理结果
    },
    error: function(res) {
        if (res.errMsg.indexOf('function_not_exist') > 0) {
            alert('版本过低请升级')
        }
    }
});

When needResult is 0, the scanning result will be processed by WeChat Enterprise, so there is no need to write operation steps in the success function; if you need to handle it yourself, set needResult to 1, and write specific operation steps in success (usually call the interface, and do logic processing in the back-end interface)

6. The overall code: (I directly use wx to report an error, and the online search import package still reports an error, so I use window.wx)

6.1 Contents in the <template> template:

Put a button, click the button to trigger the scanCode method, and call the operation inside the method

<template>
    <el-button type="danger" @click="scanCode">el-button</el-button>
  </div>
</template>

6.2 js part: (pay attention to the comments)

async function scanCode(){
      try{
          //动态获取当前页面的url地址
          const url= window.location.href.split('#')[0]
          //将url作为参数传入接口,将接口数据解构出来用data对象接受
          const {data} = await getParams(url)
          //可以将接口中数据打印出来看
          console.log("data",data)
          window.wx.config({
            beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
            debug: false, // 在测试没问题之后,关闭debug模式,防止弹窗
            appId: data.data.appId, // 必填,企业微信的corpID
            timestamp: data.data.timestamp, // 必填,生成签名的时间戳
            nonceStr: data.data.nonceStr, // 必填,生成签名的随机串
            signature: data.data.signature,// 必填,签名,见 附录-JS-SDK使用权限签名算法
            jsApiList: ["scanQRCode"] // 必填,需要使用的JS接口列表,凡是要调用的接口都需要传进来
          })
        }catch(error){
          console.log(error)
        }
      window.wx.ready(function () {
        // 调用企业微信扫一扫接口
        window.wx.scanQRCode({
          desc: "scanQRCode desc",
          needResult: 0, // 默认为0,扫描结果由企业微信处理,1则直接返回扫描结果,
          scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码(一维码),默认二者都有
            success: res => {
              // 回调
              // 当needResult 为 1 时,扫码返回的结果
              //我的vscode开启了eslint校验,定义变量而不使用会报错,在报错代码行后面跟上如下注释即可解决报错
              var result = res.resultStr// eslint-disable-line no-unused-vars
            },
            fail: function (err) {
                console.log(err)
            }
          })
        })
        window.wx.error(function(res){
          //config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
          var result = res.resultStr// eslint-disable-line no-unused-vars
          console.log("ready失败!")
        })
    }

6.3 Contents in index.js (definition of interface methods):

// 导入post请求
import { get } from "@/utiles/request.js"

// 获取企业微信扫一扫参数的接口
export const getParams = (url) => {
    return get(`http://aaa.bbb.ccc.ddd/api/getxxx?url=${url}`)
}

 

Guess you like

Origin blog.csdn.net/qq_45079530/article/details/123112281