乐趣区

关于java:企业微信自建应用配置聊天侧边栏的那些事

偶尔的一次机会,看到了企业微信聊天的侧边栏能够集成自建利用,便走走这坑路

一,关上企业微信文档,关上企业微信治理后盾并扫码登录

二,找到利用治理滑到底部,并创立利用 如下图


三,关上利用详情页



点击设置可信域名

四,java 开发

常量类,定义了微信接口名,参数等

/**
 * @author shock
 * @ClassName: WXworkConstants
 * @Description: 企业微信常量
 */
public class WxWorkConstants {

    /**
     * 微信 token 缓存 Redis 中 Key
     */
    public static final String WX_TOKEN_KEY = "qywx_access_token_key";
    /**
     * 微信 api_ticket 缓存 Redis 中 Key
     */
    public static final String WX_TICKET_KEY = "qywx_jsapi_ticket_key";
    public static final String WX_AGENT_TICKET_KEY = "qywx_agent_jsapi_ticket_key";
    /**
     *  微信 js 接口的 access_token,微信 js 接口的长期票据,有效期 7200 秒
     */
    public static final  int  EXPIRETIME = 7200;
    /**
     * 获取企业微信 token 地址及对应参数
     */
    public static final String QYWX_GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    public static final String QYWX_GET_TOKEN_URL_PARAM_CORPID = "corpid";
    public static final String QYWX_GET_TOKEN_URL_PARAM_CORPSECRET = "corpsecret";
    /**
     * 获取企业微信 token 返回胜利对应 errcode 值
     */
    public static final String QYWX_GET_TOKEN_RETURN_SUCCESS_CODE = "0";
    public static final String QYWX_GET_TOKEN_RETURN_ERRCODE = "errcode";
    public static final String QYWX_GET_TOKEN_RETURN_ERRMSG = "errmsg";
    public static final String QYWX_GET_TOKEN_RETURN_TOKEN = "access_token";

    /**
     * 获取企业微信引入 JS-SDK 的 ticket 地址及对应参数
     */
    public static final String QYWX_GET_JSAPITICKET_URL = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket";
    public static final String QYWX_GET_JSAPITICKET_URL_PARAM_TOKEN = "access_token";

    public static final String QYWX_GET_JSAPITICKET_URL_PARAM_TICKET = "jsapi_ticket";
    public static final String QYWX_GET_JSAPITICKET_URL_PARAM_NONCESTR = "noncestr";
    public static final String QYWX_GET_JSAPITICKET_URL_PARAM_TIMESTAMP = "timestamp";
    public static final String QYWX_GET_JSAPITICKET_URL_PARAM_URL = "url";

    public static final String QYWX_GET_JSAPITICKET_RETURN_SIGNATURE = "signature";
    /**
     * 获取用户 ticket 参数
     */
    public static final String QYWX_GET_JSAPITICKET_RETURN_SUCCESS_CODE = "0";
    public static final String QYWX_GET_JSAPITICKET_RETURN_ERRCODE = "errcode";
    public static final String QYWX_GET_JSAPITICKET_RETURN_ERRMSG = "errmsg";
    public static final String QYWX_GET_JSAPITICKET_RETURN_TICKET = "ticket";

    /**
     * 获取利用 ticket 相干  agentConfig
     */
    public static final String QYWX_GET_AGENT_JSAPITICKET_URL = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get";
    public static final String QYWX_GET_AGENT_JSAPITICKET_TYPE = "agent_config";
    public static final String QYWX_GET_AGENT_JSAPITICKET_PARAM = "type";

    /**
     * 通过 code 获取用户信息 url 及其对应参数
     */
    public static final String QYWX_GET_USERINFO_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
    public static final String QYWX_GET_USERINFO_URL_PARAM_TOKEN = "access_token";
    public static final String QYWX_GET_USERINFO_URL_PARAM_CODE = "code";

    /**
     * 获取客户详情 url 及其参数
     */
    public static final String QYWX_GET_CONTACT_DETAIL_URL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get";
    public static final String QYWX_GET_CONTACT_DETAIL_PARAM_TOKEN = "access_token";
    public static final String QYWX_GET_CONTACT_DETAIL_PARAM_USERID = "external_userid";
    public static final String QYWX_GET_CONTACT_DETAIL_RETURN_EXTERNAL_CONTACT = "external_contact";


    /**
     * 受权 code 用于获取企业员工信息
     */
    public static final String AUTH_BASE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?";

    /**
     * 容许的范畴
     */
    public static final String SCOPE = "snsapi_base";
    /**
     * 获取用户信息
     */
    public static final String INFO_BASE_URL = "https://api.weixin.qq.com/sns/userinfo?";
    /**
     * 回调地址
     */
    public static final String REDIRECT_URL = "http://azhen.gz.aeert.com/";
    /**
     * 依据 code 查问企业员工信息
     */
    public static final String GET_USER_INFO_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/get";
    public static final String GET_USER_INFO_PARAM_USERID = "userid";
    public static final String GET_USER_INFO_RETURN_USERID = "UserId";

    public static final String GET_USER_INFO_BY_CODE_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
    public static final String GET_USER_INFO_BY_CODE_PARAM = "code";


    /**
     * 企业微信的 CorpID,在企业微信治理端查看
     */
    public static final String QYWX_CORPID = "企业 ID";

    /**
     * 受权方的网页利用 ID,在具体的网页利用中查看
     */
    public static final String QYWX_AGENTID = "你的利用 ID";

    /**
     * 利用的凭证密钥, 在具体的网页利用中查看
     */
    public static final String QYWX_CORPSECRET = "你的秘钥";

    /**
     * 参数连接符
     */
    public static final String QYWX_AND = "&";
    public static final String QYWX_EQUAL = "=";
    public static final String QYWX_QUERY = "?";
}

申请微信接口工具类

package com.itjcloud.scrm.system.api.wx.util;


import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSONObject;
import com.itjcloud.scrm.common.utils.HttpUtils;
import com.itjcloud.scrm.system.api.wx.constans.WxWorkConstants;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author shock
 * @ClassName: WxWorkUtil
 */
public class WxWorkUtil {private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static JSONObject getSignature(String url, String ticket) {JSONObject rul = new JSONObject();
        // 生成签名字符串
        String nonceStr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String sign = "";
        sign += "jsapi_ticket=" + ticket
                + WxWorkConstants.QYWX_AND
                + "noncestr=" + nonceStr
                + WxWorkConstants.QYWX_AND
                + "timestamp=" + timestamp
                + WxWorkConstants.QYWX_AND
                + "url=" + url;
        String signature = "";
        try {
            // 指定 sha1 算法
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(sign.getBytes());
            // 获取字节数组
            byte[] messageDigest = digest.digest();
            // Create Hex String
            signature = byteToHexStr(messageDigest);
        } catch (NoSuchAlgorithmException e) {e.printStackTrace();
        }
        rul.put(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_SIGNATURE,
                signature);
        rul.put(WxWorkConstants.QYWX_GET_JSAPITICKET_URL_PARAM_NONCESTR,
                nonceStr);
        rul.put(WxWorkConstants.QYWX_GET_JSAPITICKET_URL_PARAM_TIMESTAMP,
                timestamp);
        return rul;
    }

    /**
     * 获取企业微信 token(利用调用接口凭证)该值具备以下个性:1、通用性:该企业微信利用下通用,2、* *              有效性:该值无效时长为 7200 秒,3、微信端不可长期无限度申请,举荐应用缓存保留改值
     *
     * @return
     */
    public static String getTencentToken() {
        String url = "";
        url += WxWorkConstants.QYWX_GET_TOKEN_URL
                + WxWorkConstants.QYWX_QUERY;
        url += WxWorkConstants.QYWX_GET_TOKEN_URL_PARAM_CORPID
                + WxWorkConstants.QYWX_EQUAL
                + WxWorkConstants.QYWX_CORPID;
        url += WxWorkConstants.QYWX_AND
                + WxWorkConstants.QYWX_GET_TOKEN_URL_PARAM_CORPSECRET
                + WxWorkConstants.QYWX_EQUAL;
        url += WxWorkConstants.QYWX_CORPSECRET;
        JSONObject tokenJson = UrlRequestUtil.sendGetRequest(url);
        String errcode = tokenJson
                .getString(WxWorkConstants.QYWX_GET_TOKEN_RETURN_ERRCODE);

        if (WxWorkConstants.QYWX_GET_TOKEN_RETURN_SUCCESS_CODE
                .equals(errcode)) {
            return tokenJson
                    .getString(WxWorkConstants.QYWX_GET_TOKEN_RETURN_TOKEN);
        } else {throw new RuntimeException("获取微信 Token 失败");
        }
    }

    /**
     * 依据 token 获取票据,为签名提供票据
     *
     * @param token
     * @return
     */
    public static String getTencentJSSDKTicket(String token) {
        String params = "";
        params += WxWorkConstants.QYWX_GET_JSAPITICKET_URL_PARAM_TOKEN
                + WxWorkConstants.QYWX_EQUAL + token;
        String result = HttpUtils.sendGet(WxWorkConstants.QYWX_GET_JSAPITICKET_URL, params);
        JSONObject ticketJson = JSONObject.parseObject(result);
        String errcode = ticketJson
                .getString(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_ERRCODE);
        if (WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_SUCCESS_CODE
                .equals(errcode)) {
            return ticketJson
                    .getString(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_TICKET);
        } else {throw new RuntimeException("获取微信 Ticket 失败");
        }
    }

    /**
     * 获取利用票据
     * @param token
     * @return
     */
    public static String getTencentAgentJSSDKTicket(String token) {
        String params = "";
        params += WxWorkConstants.QYWX_GET_JSAPITICKET_URL_PARAM_TOKEN
                + WxWorkConstants.QYWX_EQUAL + token;
        params += WxWorkConstants.QYWX_AND
                + WxWorkConstants.QYWX_GET_AGENT_JSAPITICKET_PARAM
                + WxWorkConstants.QYWX_EQUAL
                + WxWorkConstants.QYWX_GET_AGENT_JSAPITICKET_TYPE;

        String result = HttpUtils.sendGet(WxWorkConstants.QYWX_GET_AGENT_JSAPITICKET_URL, params);
        JSONObject ticketJson = JSONObject.parseObject(result);
        String errcode = ticketJson
                .getString(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_ERRCODE);
        if (WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_SUCCESS_CODE
                .equals(errcode)) {
            return ticketJson
                    .getString(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_TICKET);
        } else {throw new RuntimeException("获取微信 Agent Ticket 失败");
        }
    }


    /**
     * 获取客户详情
     */
    public static JSONObject getExternalcontact(String userId, String token){
        String params = "";
        params += WxWorkConstants.QYWX_GET_CONTACT_DETAIL_PARAM_TOKEN + WxWorkConstants.QYWX_EQUAL + token;
        params += WxWorkConstants.QYWX_AND;
        params += WxWorkConstants.QYWX_GET_CONTACT_DETAIL_PARAM_USERID + WxWorkConstants.QYWX_EQUAL + userId;

        String result = HttpUtils.sendGet(WxWorkConstants.QYWX_GET_CONTACT_DETAIL_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String errcode = jsonObject
                .getString(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_ERRCODE);
        if (WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_SUCCESS_CODE
                .equals(errcode)) {return jsonObject;} else {throw new RuntimeException("获取企业微信客户详情失败!");
        }
    }

    /**
     获取员工 Id
     */
    public static JSONObject getWxStaffUserId(String token, String code){

        String params = "";
        params += WxWorkConstants.QYWX_GET_CONTACT_DETAIL_PARAM_TOKEN + WxWorkConstants.QYWX_EQUAL + token;
        params += WxWorkConstants.QYWX_AND;
        params += WxWorkConstants.GET_USER_INFO_BY_CODE_PARAM + WxWorkConstants.QYWX_EQUAL + code;

        String result = HttpUtils.sendGet(WxWorkConstants.GET_USER_INFO_BY_CODE_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String errcode = jsonObject
                .getString(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_ERRCODE);
        if (WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_SUCCESS_CODE
                .equals(errcode)) {return jsonObject;} else {throw new RuntimeException("获取企业微信员工信息失败!");
        }
    }

    /**
       获取员工信息详情
     */
    public static JSONObject getWxStaffUserInfo(String token, String userId){
        String params = "";
        params += WxWorkConstants.QYWX_GET_CONTACT_DETAIL_PARAM_TOKEN + WxWorkConstants.QYWX_EQUAL + token;
        params += WxWorkConstants.QYWX_AND;
        params += WxWorkConstants.GET_USER_INFO_PARAM_USERID + WxWorkConstants.QYWX_EQUAL + userId;

        String result = HttpUtils.sendGet(WxWorkConstants.GET_USER_INFO_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String errcode = jsonObject
                .getString(WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_ERRCODE);
        if (WxWorkConstants.QYWX_GET_JSAPITICKET_RETURN_SUCCESS_CODE
                .equals(errcode)) {return jsonObject;} else {throw new RuntimeException("获取企业员工详情失败!");
        }
    }
    /**
     * 依据指定长度返回随机字符串
     *
     * @param length
     * @return 对应长度的随机字符串
     */
    private static String getRandomString(int length) {
        // 随机字符串的随机字符库
        String keyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer sb = new StringBuffer();
        int len = keyString.length();
        for (int i = 0; i < length; i++) {sb.append(keyString.charAt((int) Math.round(Math.random()
                    * (len - 1))));
        }
        return sb.toString();}

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte[] mByte) {
        int len = mByte.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串模式
        for (int j = 0; j < len; j++) {buf.append(HEX_DIGITS[(mByte[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[mByte[j] & 0x0f]);
        }
        return buf.toString();}
}

HTTP 申请封装类

package com.itjcloud.scrm.common.utils;


import com.itjcloud.scrm.common.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * 通用 http 发送办法
 * 
 * @author ruoyi
 */
public class HttpUtils
{private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送 GET 办法的申请
     *
     * @param url 发送申请的 URL
     * @param param 申请参数,申请参数应该是 name1=value1&name2=value2 的模式。* @return 所代表近程资源的响应后果
     */
    public static String sendGet(String url, String param)
    {return sendGet(url, param, Constants.UTF8);
    }

    /**
     * 向指定 URL 发送 GET 办法的申请
     *
     * @param url 发送申请的 URL
     * @param param 申请参数,申请参数应该是 name1=value1&name2=value2 的模式。* @param contentType 编码类型
     * @return 所代表近程资源的响应后果
     */
    public static String sendGet(String url, String param, String contentType)
    {StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null)
            {result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {log.error("调用 HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {log.error("调用 HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {log.error("调用 HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {log.error("调用 HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {if (in != null)
                {in.close();
                }
            }
            catch (Exception ex)
            {log.error("调用 in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();}

    /**
     * 向指定 URL 发送 POST 办法的申请
     *
     * @param url 发送申请的 URL
     * @param param 申请参数,申请参数应该是 name1=value1&name2=value2 的模式。* @return 所代表近程资源的响应后果
     */
    public static String sendPost(String url, String param, Map<String,String> headParamMap)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            headParamMap.forEach(conn::setRequestProperty);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null)
            {result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {log.error("调用 HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {log.error("调用 HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {log.error("调用 HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {log.error("调用 HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {if (out != null)
                {out.close();
                }
                if (in != null)
                {in.close();
                }
            }
            catch (IOException ex)
            {log.error("调用 in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();}

    public static String sendSSLPost(String url, String param)
    {StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try
        {log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] {new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null)
            {if (ret != null && !ret.trim().equals(""))
                {result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();}
        catch (ConnectException e)
        {log.error("调用 HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {log.error("调用 HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {log.error("调用 HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {log.error("调用 HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();}

    private static class TrustAnyTrustManager implements X509TrustManager
    {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
        { }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
        { }

        @Override
        public X509Certificate[] getAcceptedIssuers()
        {return new X509Certificate[] {};}
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {return true;}
    }
}

五,VUE

在 index.html 中引入微信的 JS SDK,还要引入一个 jwxwork sdk。不引第二个,调用一些接口报错没权限。我佛了

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>

      <!--  须要调用 JS 接口的页面引入如下 JS 文件    -->
      <script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js" type="text/javascript"></script>
      <!-- 调用 wx.agentConfig 须要引入 jwxwork sdk-->
      <script src="https://open.work.weixin.qq.com/wwopen/js/jwxwork-1.0.0.js"></script>
      <style>
          html,body{
              margin: 0 auto;
              width: 100%;
              min-width: 355px;
              height: 100%;
          }
          .el-cascader-panel {height: 120px;}
          .el-cascader-menu{min-width: 120px !important;}

          .el-cascader-node {padding: 0 10px 0 7px !important;}
          .el-cascader__suggestion-list{width: 280px !important;}
          .el-cascader-menu__wrap{width: 120px !important;}

      </style>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

次要认证企业微信的组件,重点是 wx.config 和 wx.agentConfig

<template>
    <div class="view-wrap" v-loading="loading" element-loading-text="拼命加载中">
       
        <div v-if="showLoginPage">
            <login @closeLoginPage="closeLoginPage"></login>
        </div>
    </div>
</template>

<script>
import {
    getSignature,
    getWxCustomerInfo,
    queryDictDataListMulti,
    setScrmCustomerRelation
} from '@/request/api'

import login from '@/components/login.vue'

let wx = window.wx;

export default {
    name: "CustomerDetails",
    mounted() {if (window.performance.navigation.type === 1) {this.$router.push('/')
        }else{
            // 微信认证
            this.wxConfigAuth();}

    },
    components: {login},
    data() {
        return {xxxxxxx}
    },
    methods: {
        // 进行微信认证
        wxConfigAuth(){
            let that = this
            let params = {
                // 获取以后网页 url
                "url": that.getProjectPath()}
            // 调用后盾获取签名,以及 wx.config 须要的参数。getSignature(params)
                    .then(res => {
                        let json = res.data.signature
                        let agentJson = res.data.agentSignature
                        // 注入企业的身份与权限
                        wx.config({
                            beta: true,// 必须这么写,否则 wx.invoke 调用模式的 jsapi 会有问题
                            debug: false, // 开启调试模式, 调用的所有 api 的返回值会在客户端 alert 进去,若要查看传入的参数,能够在 pc 端关上,参数信息会通过 log 打出,仅在 pc 端时才会打印。appId: res.data.appId, // 必填,企业微信的 corpID
                            timestamp: json.timestamp, // 必填,生成签名的工夫戳
                            nonceStr: json.noncestr, // 必填,生成签名的随机串
                            signature: json.signature,// 必填,签名,见附录 1
                            jsApiList: ['getContext', 'getCurExternalContact', 'navigateToAddCustomer', 'agentConfig']
                        })
                        wx.ready(function () {
                                // 如果想要在组件加载的时候就执行某些办法,则须把相干接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口,则能够间接调用,不须要放在 ready 函数中。// 以键值对的模式返回,可用的 api 值 true,不可用为 false
                                // config 配置实现还须要通过 配置 agentConfig 注入的利用的身份与权限
                                wx.agentConfig({
                                    corpid: res.data.appId, // 必填,企业微信的 corpid,必须与以后登录的企业统一
                                    agentid: res.data.agentid, // 必填,企业微信的利用 id(e.g. 1000247)timestamp: agentJson.timestamp, // 必填,生成签名的工夫戳
                                    nonceStr: agentJson.noncestr, // 必填,生成签名的随机串
                                    signature: agentJson.signature,// 必填,签名,见附录 -JS-SDK 应用权限签名算法
                                    jsApiList: ['getContext', 'getCurExternalContact'], // 必填,传入须要应用的接口名称
                                    success: () => {that.getContent()
                                    },
                                    fail: function (res) {that.errPageShow("微信认证失败,分割管理员!")
                                        if (res.errMsg.indexOf('function not exist') > -1) {alert('版本过低请降级')
                                        }
                                    }
                                })

                        })
                        wx.error(() => {
                            // 错误处理
                            that.errPageShow("微信认证失败,分割治理 3 员!")
                        })
                    })
                    .catch(err => {console.log(err)
                        // 错误处理
                        that.errPageShow("获取签名失败,分割管理员!")
                    });
        },
        // 获取进入 H5 页面的入口环境
        getContent() {
            let that = this
            wx.invoke('getContext', {}, function (res) {if (res.err_msg === "getContext:ok") {
                    // 从单聊会话的工具栏进入 single_chat_tools
                    that.entry = res.entry
                    if (that.entry === 'single_chat_tools') {that.getCurExternalContact()
                    } else {
                        // 错误处理
                        that.errPageShow("请在企业微信中关上该网址!")
                    }
                    // shareTicket = res.shareTicket; // 可用于调用 getShareInfo 接口
                } else {that.errPageShow("获取环境失败,分割管理员!")
                    return false;
                }
            })
        },

        // 企业微信获取以后客户 userId
        getCurExternalContact() {
            let that = this
            wx.invoke('getCurExternalContact', {}, function (res) {if (res.err_msg == "getCurExternalContact:ok") {
                    // 返回以后内部联系人 userId
                    let userId = res.userId
                    that.wxUserId = userId;
                    sessionStorage.setItem("wxUserId", userId);
                    // 受权后,依据 scrmAuthStatus 判断接下来的操作
                    that.getWxUserIdAfter(userId)
                } else {that.$message.warning("获取企业微信 userID 失败,请分割管理员");
                }
            })
        },
   
        // 失去以后我的项目的 url
        getProjectPath() {let url = window.self.location.toString()
            return url
        },


    }
}
</script>

<style lang="less" scoped>
.view-wrap {
    width: 100%;
    height: 100%;
}

// 微信环境
.view-wx {
    width: 100%;
    height: 100%;
}

// 非微信环境
.view-err {
    width: 100%;
    height: 100%;
    text-align: center;
    font-size: 18px;
    margin-top: 30px;
    color: #333333;
}

.customer_flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.customer_center_flex {
    display: flex;
    justify-content: center;
    align-items: center;
}

.customer_detail {
    height: 100%;
    width: 100%;
    // padding: 0 5px;
    // box-sizing: border-box;
    .top {
        padding: 10px;
        box-sizing: border-box;
        border: 1px solid #DEE0E2;

        .portrait {
            width: 40px;
            height: 40px;

            img {width: 100%;}
        }

        .top_right {
            width: 85%;

            .customer_name {
                text-align: left;
                line-height: 10px;

                .title {
                    font-size: 15px;
                    font-weight: Regular;
                    color: #333333;
                }

                .shop {
                    font-size: 12px;
                    font-weight: Regular;
                    color: #3154EF;
                }
            }
        }

    }

}

/deep/ .el-button--danger {background-color: #F6382B;}

/deep/ .el-tabs__item {padding: 0;}

/deep/ .el-tabs__content {height: calc(100vh - 200px);
    overflow: auto;
}
</style>

六,坑

1,因为须要可信域名,而我应用花生壳内网穿透的,收费的网很慢~

2,企业微信是有调试台的,教程移步:企业微信开启调试模式

3,企业微信获取客户 (内部联系人) 的 userid 很容易,不晓得为啥获取以后登录员工的 userid 却那么吃力,只好走企业微信的 结构网页受权链接进行重定向获取 code(这个 code 只能生产一次,有效期为 5 分钟), 再通过 code 获取员工 userid, 再通过 userid 获取员工手机号等详细信息。

4,vue 的 vue.config.js 的 publicPath: ‘/’, 慎改

5,大坑图示要配置,利用,否则客户相干接口没权调用

6,ok

退出移动版