wxConfig.js 9.39 KB
import util from '@/utils/util'
import { Notify } from 'vant'
let requestCount = 0
let wwRequestCount = 0
const WxConfig = {
  async init (jsApiList = []) {
    const isWxWork = window.$ISWXWORK
    jsApiList.map(e => {
      if (e == 'chooseImage') jsApiList.push('getLocalImgData')
    })
    await this[isWxWork ? 'getWWConfig' : 'getWxConfig'](jsApiList)
  },
  getWWConfig (jsApiList) {
    wwRequestCount += 1
    let [redirectUrl] = window.location.href.split('#')
    return new Promise((resolve) => {
      const STORAGE_PARAMS = util.getLocalStorage('wx_scrm_link_params')
      let data = {
        corpId: STORAGE_PARAMS.corpId,
        method: 'scrm.api.work.wechat.get.agent.config',
        url: redirectUrl,
        appCode: 'DJQWGJ'
      }
      this.getWxConfig(jsApiList).then(() => {
        wx.ready(() => {
          window.$HTTP({
            url: '/rop-scrm-wechat/router',
            data,
            returnAll: true
          }).then(({ code, data, message }) => {
            if (code == '0') {
              if (data) {
                wx.agentConfig({
                  corpid: data.corpId, // 必填,企业微信的corpid,必须与当前登录的企业一致
                  agentid: data.agentId, // 必填,企业微信的应用id (e.g. 1000247)
                  timestamp: data.timestamp, // 必填,生成签名的时间戳
                  nonceStr: data.nonceStr, // 必填,生成签名的随机串
                  signature: data.signature, // 必填,签名,见附录-JS-SDK使用权限签名算法,
                  jsApiList: ['getContext', ...jsApiList],
                  success (res) {
                    resolve()
                  },
                  fail (err) {
                    Notify(message)
                    // util.refreshPage(JSONStringify(err)).then(() => {
                    //   window.location.reload()
                    // })
                  }
                })
              } else {
                if (wwRequestCount < 3) this.getWWConfig(jsApiList)
                else Notify(message)
                // util.refreshPage('获取WWCONFIG失败').then(() => {
                //   window.location.reload()
                // })
              }
            } else {
              if (wwRequestCount < 3) this.getWWConfig(jsApiList)
              else Notify(message)
              // util.refreshPage(message).then(() => {
              //   window.location.reload()
              // })
            }
          })
        })
      })
    })
  },
  getWxConfig (jsApiList) {
    requestCount += 1
    let [redirectUrl] = window.location.href.split('#')
    return new Promise((resolve) => {
      window.$HTTP({
        url: '/rop-scrm-equity/router',
        data: {
          url: redirectUrl,
          appId: window.$fetchConfig.appid,
          method: 'scrm.api.equity.common.wechat.jsconfig'
        },
        returnAll: true
      }).then(({ code, data, message }) => {
        if (code == '0') {
          if (data) {
            let obj = {}
            Object.keys(data).map(key => {
              if (data[key]) obj[key] = data[key]
            })
            wx.config({
              ...obj,
              jsApiList,
              openTagList: ['wx-open-launch-weapp']
            })
            resolve()
          } else {
            if (requestCount < 3) this.getWxConfig(jsApiList)
            else Notify(message)
            // util.refreshPage('获取WXCONFIG失败').then(() => {
            //   window.location.reload()
            // })
          }
        } else {
          if (requestCount < 3) this.getWxConfig(jsApiList)
          else Notify(message)
          // util.refreshPage(message).then(() => {
          //   window.location.reload()
          // })
        }
      })
    })
  },
  ready (callBack) {
    const isWxWork = window.$ISWXWORK
    return new Promise((resolve, reject) => {
      if (isWxWork) wx.invoke('getContext', {}, res => {
        let { err_msg, entry, shareTicket } = res
        /** entry 说明
         *contact_profile	从联系人详情进入	3.0.24
         *single_chat_tools	从单聊会话的工具栏进入	3.0.24
         *group_chat_tools	从群聊会话的工具栏进入	3.0.24
         *chat_attachment	从会话的聊天附件栏进入	3.1.6
         *normal	除以上场景之外进入,例如工作台,聊天会话等	3.0.24
         **/
        if (err_msg == 'getContext:ok') {
          //entry 返回进入H5页面的入口类型,目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
          //shareTicket可用于调用getShareInfo接口
          callBack(resolve({
            entry,
            shareTicket
          }), reject)
        } else {
          callBack(reject)
        }
      })
      else wx.ready(() => {
        callBack(resolve, reject)
      })
    })
  },
  /**获取地理位置接口 */
  getLocation (type = 'gcj02') {
    return this.ready((resolve) => {
      wx.getLocation({
        type, // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
        success (res) {
          resolve(res)
        }
      })
    })
  },
  /**打开地图导航 */
  openLocation (params) {
    return this.ready(resolve => {
      let { latitude, longitude, name, address, scale = '18', infoUrl = '' } = params
      wx.openLocation({
        latitude,
        longitude,
        name,
        address,
        scale,
        infoUrl,
        success (res) {
          console.log(res)
          resolve(res)
        }
      })
    })
  },
  /**支付 */
  chooseWXPay ({ timestamp, nonceStr, packages, signType, paySign }) {
    return this.ready(resolve => {
      wx.chooseWXPay({
        timestamp, // 支付签名时间戳,注意微信js sdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        nonceStr, // 支付签名随机串,不长于 32 位
        package: packages, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
        signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
        paySign, // 支付签名
        success (res) {
          window.vm.showToast('支付成功')
          resolve(res)
        },
        fail () {
          window.vm.showToast('已取消支付')
        },
        cancel () {
          window.vm.showToast('支付失败,请重试')
        }
      })
    })
  },
  /**设置分享内容 */
  updateAppMessageShareData (params) {
    // title, // 分享标题
    // desc: '', // 分享描述
    // link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
    // imgUrl: '', // 分享图标
    return this.ready(resolve => {
      wx.updateAppMessageShareData({
        ...params,
        success: function () {
          resolve()
          // 设置成功
        }
      })
    })
  },
  /**分享朋友圈内容 */
  updateTimelineShareData (params) {
    delete params.desc
    // title, // 分享标题
    // link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
    // imgUrl: '', // 分享图标
    return this.ready(resolve => {
      wx.updateTimelineShareData({
        ...params,
        success: function () {
          resolve()
          // 设置成功
        }
      })
    })
  },
  /**获取“分享给朋友”按钮点击状态及自定义分享内容接口(即将废弃) */
  /**
   * title: '', // 分享标题
   * desc: '', // 分享描述
   * link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
   * imgUrl: '', // 分享图标
   * type: '', // 分享类型,music、video或link,不填默认为link
   * dataUrl: '', // 如果 type 是music或video,则要提供数据链接,默认为空
   */
  onMenuShareAppMessage (params) {
    return new Promise((resolve) => {
      wx.onMenuShareAppMessage({
        ...params,
        success: function () {
          resolve()
          // 用户点击了分享后执行的回调函数
        },
      })
    })
  },
  /**获取“分享到朋友圈”按钮点击状态及自定义分享内容接口(即将废弃) */
  onMenuShareTimeline (params) {
    delete params.desc
    return new Promise((resolve) => {
      wx.onMenuShareTimeline({
        ...params,
        success: function () {
          resolve()
          // 用户点击了分享后执行的回调函数
        },
      })
    })
  },
  /**企微自定义转发到会话 */
  shareAppMessage (params) {
    // title: '', // 分享标题
    // desc: '', // 分享描述
    // link: '', // 分享链接
    // imgUrl: '' // 分享封面
    return new Promise((resolve, reject) => {
      wx.invoke('shareAppMessage', params, function (res) {
        util.hideLoading()
        if (res.err_msg == 'shareAppMessage:ok') resolve(res)
        else reject(res)
      })
    })
  },
  /**企微跳转到小程序 
   * 
      "appid": "wx062aaa5507909631", // 需跳转的小程序appid
      "path": "pages/home/index.html", // 所需跳转的小程序内页面路径及参数。非必填
   * 
  */
  launchMiniprogram (params) {
    return new Promise((resolve, reject) => {
      wx.invoke('launchMiniprogram', params, function (res) {
        if (res.err_msg == "launchMiniprogram:ok") resolve(res)
        else reject(res)
      })
    })
  }
}

export default WxConfig