aCommon.js 13.3 KB
Newer Older
Z's avatar
Z committed
1 2 3 4 5
import Vue from 'vue'
import { wxRequest } from './aWxRequest'
import qs from 'qs'
import router from '../router'

6 7
const zlog = console.log.bind(console)

Z's avatar
Z committed
8 9
// Z-BasicInfo
let INFO = {
10 11 12 13
  // corpId: 'wwd1cdbca7b8b2b6c4',
  // agentId: '1000015',
  corpId: 'ww4df265003b43fa0d',
  agentId: '1000032',
Z's avatar
Z committed
14 15 16 17 18 19 20 21
}

async function getXToken() {
  let postData = {
    corpId: INFO.corpId,
    agentId: INFO.agentId,
  }

22
  console.log('%c--->getXToken: PD =', 'background: orange;', postData)
Z's avatar
Z committed
23
  await wxRequest('/workWx/common/getToken', qs.stringify(postData)).then(res => {
24
    if (res.result === 'success') {
Z's avatar
Z committed
25
      sessionStorage.setItem('XToken', res.data)
26 27

      console.log('%c--->getXToken: RD =', 'background: limegreen;', res)
Z's avatar
Z committed
28
    } else {
29 30
      console.log('%c--->getXToken: N/A. ', 'background: red;')

xulili's avatar
xulili committed
31 32 33 34
      // this.$message({
      //   message: res.errorMsg,
      //   type: 'error'
      // })
Z's avatar
Z committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    }
  }).catch(err => {
    console.log('!==>getXToken: err:', err)
  })
}

function isIosOrAndroid() {
  let u = navigator.userAgent;
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
  let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
  let isStr = ''
  if (isAndroid) {
    isStr = 'android'
  }
  if (isiOS) {
    isStr = 'ios'
  }
  return isStr
}

Vue.prototype.getAgentAuth = function () {
  let postData = {
    // businessId: sessionStorage.getItem('businessId'),
    // pageUrl: encodeURIComponent(this.isIosOrAndroid() === 'android' ? location.href.split('#')[0] : window.initUrl)
    pageUrl: encodeURIComponent(location.href.split('#')[0])
  }
61 62
  // alert(`--->zCommon.js: postData =${JSON.stringify(postData)}`)

Z's avatar
Z committed
63 64 65 66 67
  let header = {
    token: sessionStorage.getItem('XToken'),
    corpId: INFO.corpId,
    agentId: INFO.agentId,
  }
68 69
  // alert(`--->zCommon.js: header =${JSON.stringify(header)}`)

70 71
  console.log('%c--->getAgentAuth: getJsSdkSignature: PD =', 'background: orange;', header)

72 73 74 75
  wxRequest('/workWx/auth/base/getJsSdkSignature', qs.stringify(postData), header)
    .then(res => {
      // alert(`--->zCommon.js: getJsSdkSignature: then.`)
      // alert(`--->zCommon.js: getJsSdkSignature: then: res =${JSON.stringify(res)}`)
76

77 78 79
      if (res.result === 'success') {
        console.log('%c--->getAgentAuth: getJsSdkSignature: RD =', 'background: limegreen;', res.data)
        // alert(`--->zCommon.js: getJsSdkSignature: then: res.result === "success".`)
80

81 82 83
        let config = res.data
        wx.config({
          beta: true,
xulili's avatar
xulili committed
84
          debug: false, //调试的时候可以开启
85 86 87 88 89
          appId: config.jsApiSignature.appId, // 必填,公众号的唯一标识
          timestamp: config.jsApiSignature.timestamp, // 必填,生成签名的时间戳
          nonceStr: config.jsApiSignature.nonceStr, // 必填,生成签名的随机串
          signature: config.jsApiSignature.signature, // 必填,签名
          // 根据自己的需求,填写 jsapilist 内容
90 91 92 93 94
          jsApiList: ['agentConfig', 'sendChatMessage'],
          success: function(res) {
          },
          fail: function(err) {
          }
Z's avatar
Z committed
95
        })
96

97 98 99 100 101 102 103 104 105 106 107 108
        // alert(`--->zCommon.js: getJsSdkSignature: then: wx.config: end.`)
        wx.ready(function () {
          zlog('%c--->getAgentAuth: getJsSdkSignature: Ready.', 'color: red;')
          // alert(`--->zCommon.js: getJsSdkSignature: then: wx.ready: IN.`)

          // JS-SDK配置信息验证失败时会进入此方法
          wx.error(function (res) {
          })

          // 配置成功后验证API接口在当前客户端是否支持:判断当前客户端版本是否支持指定JS接口
          wx.checkJsApi(
            {
109
              jsApiList: ['config', 'agentConfig', 'sendChatMessage'],
110 111
              success: function (res) {
                if (res.errMsg != "checkJsApi:ok") {
xd's avatar
xd committed
112
                  // alert("JS-SDK接口检测失败:" + JSON.stringify(res));
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
                  return false;
                } else {
                  wxRequest('/workWx/auth/base/getAgentJsSdkSignature', qs.stringify(postData), header)
                  .then(res => {
                    // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: res.`)
                    // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: res =${JSON.stringify(res)}`)

                    // alert('getAgentJsSdkSignature:ok')
                    if (res.result === 'success') {
                      let agentConfig = res.data
                      wx.agentConfig({
                        corpid: agentConfig.agentJsApiSignature.appId, // 必填,企业微信的 corpid,必须与当前登录的企业一致
                        agentid: agentConfig.agentId, // 必填,企业微信的应用id
                        timestamp: agentConfig.agentJsApiSignature.timestamp, // 必填,生成签名的时间戳
                        nonceStr: agentConfig.agentJsApiSignature.nonceStr, // 必填,生成签名的随机串
                        signature: agentConfig.agentJsApiSignature.signature,// 必填,签名,agentConfig所以为应用签名
                        jsApiList: ['sendChatMessage'], //必填
                        success: function (res) {
xd's avatar
xd committed
131
                          // alert('agentConfigSuccess')
132 133 134 135 136 137 138 139 140 141
                          // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: wx.agentConfig: res.`)
                          // alert(`!-->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: wx.agentConfig: res =${JSON.stringify(res)}`)
                          // alert('agentConfig:ok')
                          // router.push(to)
                          // 回调
                          //1、发起申请申请时后,审批状态发生变化时
                          //2、发起申请申请时后,在“审批中”状态,有任意审批人进行审批操作时
                          // alert('wx.agentConfig 回调'+res.errMsg);
                        },
                        fail: function (res) {
xd's avatar
xd committed
142
                          // alert('agentConfigFailed')
143 144 145 146 147 148 149
                          // alert('回调失败:'+res.errMsg)
                          if (res.errMsg.indexOf('is not a function') > -1) {
                            alert('<i class="weui-icon-warn">版本过低请升级</i>')
                          }
                        }
                      })

Z's avatar
Z committed
150 151
                    }
                  })
152 153 154 155
                  .catch(err => {
                    // alert(`--->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: err.`)
                    // alert(`--->zCommon.js: getJsSdkSignature: then: wx.ready: wx.checkJsApi: getAgentJsSdkSignature: err =${JSON.stringify(err)}`)
                  })
Z's avatar
Z committed
156
                }
157
              }
Z's avatar
Z committed
158
            }
159
          )
Z's avatar
Z committed
160
        })
161
      } else {
xulili's avatar
xulili committed
162 163 164 165
        // this.$message({
        //   type: 'error',
        //   message: res.errorMsg
        // })
166 167 168 169 170 171 172
      }
    })
    .catch(err => {
      // alert(`--->zCommon.js: getJsSdkSignature: catch.`)
      // alert(`--->zCommon.js: getJsSdkSignature: catch: err =${JSON.stringify(err)}`)
      console.log(err, 'err')
    })
Z's avatar
Z committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
}

function configWx(to) {
  let postData = {
    // businessId: sessionStorage.getItem('businessId'),
    // pageUrl: encodeURIComponent(this.isIosOrAndroid() === 'android' ? location.href.split('#')[0] : window.initUrl)
    pageUrl: encodeURIComponent(location.href.split('#')[0])
  }
  let header = {
    token: sessionStorage.getItem('XToken'),
    corpId: INFO.corpId,
    agentId: INFO.agentId,
  }
  wxRequest('/workWx/auth/base/getJsSdkSignature', qs.stringify(postData), header).then(res => {
    if (res.result == 'success') {
      let config = res.data
      wx.config({
        beta: true,
xulili's avatar
xulili committed
191
        debug: false, //调试的时候可以开启
Z's avatar
Z committed
192 193
        appId: config.jsApiSignature.appId, // 必填,公众号的唯一标识
        timestamp: config.jsApiSignature.timestamp, // 必填,生成签名的时间戳
xulili's avatar
xulili committed
194
        nonceStr: config.jsApiSignature.nonceStr, // 必填,生成签名的随机串
Z's avatar
Z committed
195 196
        signature: config.jsApiSignature.signature, // 必填,签名
        // 根据自己的需求,填写 jsapilist 内容
197
        jsApiList: ['agentConfig', 'getCurExternalContact']
Z's avatar
Z committed
198 199 200 201 202 203 204 205 206
      })
      wx.ready(function () {
        // JS-SDK配置信息验证失败时会进入此方法
        wx.error(function (res) {
        })
        // 配置成功后验证API接口在当前客户端是否支持:判断当前客户端版本是否支持指定JS接口
        wx.checkJsApi({
          jsApiList: ['agentConfig', 'getCurExternalContact'],
          success: function (res) {
207 208 209
            // alert(`--->wx.checkJsApi: success. res =${JSON.stringify(res)}`);
            // router.push(to)

Z's avatar
Z committed
210
            if (res.errMsg != "checkJsApi:ok") {
xulili's avatar
xulili committed
211
              // alert("JS-SDK接口检测失败:" + JSON.stringify(res));
Z's avatar
Z committed
212 213 214 215 216
              return false;
            }
          }
        })

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        // alert(`--->configWx/getJsSdkSignature: next: getAgentJsSdkSignature.`)
        // alert(`--->configWx/getJsSdkSignature: next: getAgentJsSdkSignature: data =${qs.stringify(postData)}. header =${JSON.stringify(header)}`)

        wxRequest('/workWx/auth/base/getAgentJsSdkSignature', qs.stringify(postData), header)
          .then(res => {
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: IN.`)
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: res =${JSON.stringify(res)}`)

            if (res.result == 'success') {
              let agentConfig = res.data
              // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: res.result == 'success'.`)

              wx.agentConfig({
                corpid: agentConfig.agentJsApiSignature.appId, // 必填,企业微信的corpid,必须与当前登录的企业一致
                agentid: agentConfig.agentId, // 必填,企业微信的应用id
                timestamp: agentConfig.agentJsApiSignature.timestamp, // 必填,生成签名的时间戳
                nonceStr: agentConfig.agentJsApiSignature.nonceStr, // 必填,生成签名的随机串
                signature: agentConfig.agentJsApiSignature.signature,// 必填,签名,agentConfig所以为应用签名
                jsApiList: ['getCurExternalContact'], //必填
                success: function (res) {
xulili's avatar
xulili committed
237
                  // alert('agentConfig:ok')
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                  // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: agentConfig: res =${res}`)
                  // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: then: agentConfig: to =${JSON.stringify(to)}`)
                  sessionStorage.setItem('zConfigWx', 'Pass')

                  router.push(to)
                  // getUnionid(to)
                  // 回调
                  //1、发起申请申请时后,审批状态发生变化时
                  //2、发起申请申请时后,在“审批中”状态,有任意审批人进行审批操作时
                  // alert('wx.agentConfig 回调'+res.errMsg);
                },
                fail: function (res) {
                  if (res.errMsg.indexOf('is not a function') > -1) {
                    alert('<i class="weui-icon-warn">版本过低请升级</i>')
                  }
Z's avatar
Z committed
253
                }
254 255 256 257 258 259 260
              })
            }
          })
          .catch(err => {
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: catch: err.`)
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: catch: err =${JSON.stringify(err)}`)
          })
Z's avatar
Z committed
261 262
      })
    } else {
xulili's avatar
xulili committed
263 264 265 266
      // this.$message({
      //   type: 'error',
      //   message: res.errorMsg
      // })
Z's avatar
Z committed
267 268 269 270 271 272 273 274 275 276 277
    }
  }).catch(err => {
    console.log(err, 'err')
  })
}

function getUnionid(to) {
  wx.invoke('getCurExternalContact', {}, function (res) {
    if (res.err_msg == "getCurExternalContact:ok") {
      let header = {
        token: sessionStorage.getItem('XToken'),
Z's avatar
Z committed
278 279
        corpId: INFO.corpId,
        agentId: INFO.agentId,
Z's avatar
Z committed
280 281 282 283 284 285 286
      }
      let postData = {
        userId: res.userId
      }
      wxRequest('/workWx/auth/contact/getExternalContact', postData, header, 'get').then(res => {
        if (res.result == 'success') {
          sessionStorage.setItem('unionid', res.data.externalContact.unionId)
287
          console.log('%c--->UnionId: RES: ', 'background: limegreen;', res.data.externalContact.unionId)
Z's avatar
Z committed
288 289 290 291
          router.push(to)
        }
      })
    } else {
292 293 294 295 296 297 298 299 300 301 302
      console.log('%c--->UnionId: N/A', 'background: red;')
      console.log(res, 'res')
    }
  });
}

function getUserInfo(inData) {
  wx.invoke('getUserInfo', {}, function (res) {
    if (res.err_msg == "getUserInfo:ok") {
      let header = {
        token: sessionStorage.getItem('XToken'),
Z's avatar
Z committed
303 304
        corpId: INFO.corpId,
        agentId: INFO.agentId,
305 306 307 308 309 310 311 312 313 314 315 316 317
      }
      let postData = {
        code: inData.code
      }
      wxRequest('/workWx/auth/oauth2/getUserInfo', postData, header, 'post').then(res => {
        if (res.result == 'success') {
          sessionStorage.setItem('userInfo', res.data)
          console.log('%c--->getUserInfo: RES: ', 'background: limegreen;', res.data)
          // router.push(to)
        }
      })
    } else {
      console.log('%c--->UnionId: N/A', 'background: red;')
Z's avatar
Z committed
318 319 320 321 322 323
      console.log(res, 'res')
    }
  });
}


324
export { getXToken, configWx, getUnionid, getUserInfo }