base.js 1.72 KB
Newer Older
zhanghaozhe committed
1
/* global wx */
zhanghaozhe committed
2
import { http, browser } from "src/utils"
3

xuzhenghua committed
4 5
// const url = `https://res.wx.qq.com/open/js/jweixin-1.4.0.js`
const url = `https://res.wx.qq.com/open/js/jweixin-1.6.0.js`
zhanghaozhe committed
6 7 8 9 10 11 12
const appId = "wx23dac6775ac82877"
const jsApiList = [
  "updateAppMessageShareData",
  "updateTimelineShareData",
  "onMenuShareAppMessage",
  "onMenuShareTimeline",
]
13 14

export const getSignature = async (config = {}) => {
zhanghaozhe committed
15 16 17 18 19
  let res = await http.post(`${API["base-api"]}/m/sale/signature`, {
    url:
      browser.isWeixin && browser.isIOS
        ? sessionStorage.getItem("enter_url")
        : window.location.href.split("#")[0],
xuzhenghua committed
20 21 22 23 24 25
  })
  return wx.config({
    debug: false, // 开启调试模式,
    appId, // 必填,公众号的唯一标识
    timestamp: res.data.timestamp, // 必填,生成签名的时间戳
    nonceStr: res.data.nonce_str, // 必填,生成签名的随机串
zhanghaozhe committed
26
    signature: res.data.signature, // 必填,签名,见附录1
xuzhenghua committed
27
    jsApiList,
zhanghaozhe committed
28
    ...config,
xuzhenghua committed
29
  })
30 31 32
}

export const getWXObject = () => {
zhanghaozhe committed
33
  return new Promise((resolve) => {
xuzhenghua committed
34 35 36 37 38
    if (!window.wx) {
      return loadScript(url).then(() => resolve())
    }
    resolve()
  })
39 40 41
}

function loadScript(url) {
zhanghaozhe committed
42 43 44
  return new Promise((resolve) => {
    var head = document.head || document.getElementsByTagName("head")[0]
    var script = document.createElement("script")
xuzhenghua committed
45

zhanghaozhe committed
46
    script.type = "text/javascript"
xuzhenghua committed
47 48
    script.src = url

zhanghaozhe committed
49
    if (!("onload" in script)) {
xuzhenghua committed
50
      script.onreadystatechange = function () {
zhanghaozhe committed
51 52
        if (this.readyState !== "complete" && this.readyState !== "loaded")
          return
xuzhenghua committed
53 54 55 56 57 58 59 60 61 62 63 64 65
        this.onreadystatechange = null
        resolve()
      }
    }

    script.onload = function () {
      this.onload = null
      resolve()
    }

    head.appendChild(script)
  })
}