aCommon copy.js 13.4 KB
Newer Older
xd's avatar
xd committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
import Vue from 'vue'
import { wxRequest } from './aWxRequest'
import qs from 'qs'
import router from '../router'

const zlog = console.log.bind(console)

// Z-BasicInfo
let INFO = {
  // corpId: 'wwd1cdbca7b8b2b6c4',
  // agentId: '1000015',
  corpId: 'ww4df265003b43fa0d',
  agentId: '1000033',
}

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

  console.log('%c--->getXToken: PD =', 'background: orange;', postData)
  await wxRequest('/workWx/common/getToken', postData,'get').then(res => {
    if (res.result === 'success') {
      sessionStorage.setItem('XToken', res.data)
      console.log('%c--->getXToken: RD =', 'background: limegreen;', res)
    } else {
      console.log('%c--->getXToken: N/A. ', 'background: red;')

      // this.$message({
      //   message: res.errorMsg,
      //   type: 'error'
      // })
    }
  }).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 () {
  zlog('%c--->IN: getAgentAuth: location.href =', 'color: orange;', location.href)
  // alert(`--->zCommon.js: IN.`)

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

  let header = {
    token: sessionStorage.getItem('XToken'),
    corpId: INFO.corpId,
    agentId: INFO.agentId,
  }
  // alert(`--->zCommon.js: header =${JSON.stringify(header)}`)

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

  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)}`)

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

        let config = res.data
        wx.config({
          beta: true,
          debug: false, //调试的时候可以开启
          appId: config.jsApiSignature.appId, // 必填,公众号的唯一标识
          timestamp: config.jsApiSignature.timestamp, // 必填,生成签名的时间戳
          nonceStr: config.jsApiSignature.nonceStr, // 必填,生成签名的随机串
          signature: config.jsApiSignature.signature, // 必填,签名
          // 根据自己的需求,填写 jsapilist 内容
          jsApiList: ['agentConfig']
        })

        // 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) {
            // alert("JS-SDK配置信息验证失败 \r\n" + JSON.stringify(res));
          })

          // 配置成功后验证API接口在当前客户端是否支持:判断当前客户端版本是否支持指定JS接口
          wx.checkJsApi(
            {
              jsApiList: ['agentConfig', 'sendChatMessage'],
              success: function (res) {
                if (res.errMsg != "checkJsApi:ok") {
                  // alert("JS-SDK接口检测失败:" + JSON.stringify(res));
                  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) {
                          // 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) {
                          // alert('回调失败:'+res.errMsg)
                          if (res.errMsg.indexOf('is not a function') > -1) {
                            alert('<i class="weui-icon-warn">版本过低请升级</i>')
                          }
                        }
                      })

                    }
                  })
                  .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)}`)
                  })
                }
              }
            }
          )
        })
      } else {
        // this.$message({
        //   type: 'error',
        //   message: res.errorMsg
        // })
      }
    })
    .catch(err => {
      // alert(`--->zCommon.js: getJsSdkSignature: catch.`)
      // alert(`--->zCommon.js: getJsSdkSignature: catch: err =${JSON.stringify(err)}`)
      console.log(err, 'err')
    })
}

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,
        debug: false, //调试的时候可以开启
        appId: config.jsApiSignature.appId, // 必填,公众号的唯一标识
        timestamp: config.jsApiSignature.timestamp, // 必填,生成签名的时间戳
        nonceStr: config.jsApiSignature.nonceStr, // 必填,生成签名的随机串
        signature: config.jsApiSignature.signature, // 必填,签名
        // 根据自己的需求,填写 jsapilist 内容
        jsApiList: ['agentConfig', 'getCurExternalContact']
      })
      wx.ready(function () {
        // JS-SDK配置信息验证失败时会进入此方法
        wx.error(function (res) {
          // alert("JS-SDK配置信息验证失败 \r\n" + JSON.stringify(res))
        })
        // 配置成功后验证API接口在当前客户端是否支持:判断当前客户端版本是否支持指定JS接口
        wx.checkJsApi({
          jsApiList: ['agentConfig', 'getCurExternalContact'],
          success: function (res) {
            // alert(`--->wx.checkJsApi: success. res =${JSON.stringify(res)}`);
            // router.push(to)

            if (res.errMsg != "checkJsApi:ok") {
              // alert("JS-SDK接口检测失败:" + JSON.stringify(res));
              return false;
            }
          }
        })

        // 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) {
                  // alert('agentConfig:ok')
                  // 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) {
                  // alert(`--->A: err =${res}`)
                  // alert(`--->A: err =${JSON.stringify(res)}`)

                  if (res.errMsg.indexOf('is not a function') > -1) {
                    // alert('<i class="weui-icon-warn">版本过低请升级</i>')
                  }
                }
              })
            }
          })
          .catch(err => {
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: catch: err.`)
            // alert(`--->configWx/getJsSdkSignature/getAgentJsSdkSignature: catch: err =${JSON.stringify(err)}`)
          })
      })
    } else {
      // this.$message({
      //   type: 'error',
      //   message: res.errorMsg
      // })
    }
  }).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'),
        corpId: INFO.corpId,
        agentId: INFO.agentId,
      }
      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)
          console.log('%c--->UnionId: RES: ', 'background: limegreen;', res.data.externalContact.unionId)
          router.push(to)
        }
      })
    } else {
      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'),
        corpId: INFO.corpId,
        agentId: INFO.agentId,
      }
      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;')
      console.log(res, 'res')
    }
  });
}


export { getXToken, configWx, getUnionid, getUserInfo }