wwf
17 小时以前 4e6f18dfa08e2f2f4f02aaa1b8e8e51852b7a9a1
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
326
327
328
329
330
331
332
333
334
import wx from 'weixin-js-sdk'
import axios from './axios'
import store from '../store.js'
import $qxueyou from '@/config/qxueyou.js'
import utilsUA from '@/plugins/utilsUA'
import { getUUID, qxyResImg } from '@/plugins/utils'
 
let newFeature = false
let oldShare = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone']
let newShare = ['updateTimelineShareData', 'updateAppMessageShareData']
 
let weixinFlag = utilsUA.isWeixin
let mobileFlag = utilsUA.isMobile
let channel = weixinFlag && mobileFlag ? 'wx_pub' : 'wx_pub_qr'
let isWxpub = 'wx_pub'.includes(channel)
 
/**
 * 微信获取签名
 * @param {*} toRoute 目标路由
 */
function getWxSignature(toRoute) { 
  if (!weixinFlag) { return false }
 
  axios.get('/wx/js/signature', {
    params: { url: location.href } 
  }).then(res => {
    if (!res || !res.data) {
      return false
    }
    let result = res.data.data || {}
    wx.config({ // 微信配置
      debug: false,
      appId: result.appId,
      timestamp: result.timestamp,
      nonceStr: result.nonceStr,
      signature: result.signature,
      jsApiList: [
        ...(newFeature ? newShare : oldShare),
        'chooseWXPay',
        'chooseImage',
        'getLocalImgData'
      ],
      openTagList: ['wx-open-launch-app']
    })
    wx.ready(function () {
      initShareOption(toRoute)
    })
    wx.error(function (res) {
      console.log(res)
    })
  })
}
 
/**
 * 初始化分享数据
 * @param {*} toRoute 
 */
function initShareOption(toRoute) {
  if (!weixinFlag) { return false }
 
  let uuid = getUUID()
  let shareOptions = getShareOptions(uuid,toRoute)
 
  shareOptions.success = function () {
    shareSuccess(uuid,toRoute)
  }
  shareOptions.cancel = function () {
    console.log('取消分享')
  }
  shareOptions.trigger = function () {
    console.log('用户点击发送给朋友')
  }
 
  // 向下兼容旧版分享接口
  if (!newFeature) {
    wx.onMenuShareTimeline(shareOptions)
    wx.onMenuShareAppMessage(shareOptions)
  } else {
    wx.updateAppMessageShareData(shareOptions)
    wx.updateTimelineShareData(shareOptions)
  }
}
 
/**
 * 获取分享数据
 * @param {*} list 
 */
function getShareOptions(uuid,toRoute) {
  let result = {}
  let customShare = store.state.share.custom
  if (customShare.title) {
    result.title = customShare.title
    result.desc = customShare.desc
  } else {
    result.title = toRoute.name
    result.desc = toRoute.name
  }
  if (customShare.imgUrl) {
    if (customShare.imgUrl.includes('http')) {
      result.imgUrl = customShare.imgUrl
    } else {
      result.imgUrl = qxyResImg(customShare.imgUrl)
    }
  }
 
  if (customShare.uuidLink) {
    let pageUrl = customShare.pageUrl || toRoute.fullPath
    let encode = encodeURI(`${uuid},${$qxueyou.htmlRoot + pageUrl}`)
    result.link = customShare.uuidLink + btoa(encode)
    // result.link = customShare.uuidLink + uuid
  } else if (customShare.link) {
    result.link = customShare.link
  } else {
    result.link = location.href
  }
 
  return result
}
 
/**
 * 分享成功回调
 */
function shareSuccess(uuid,toRoute) {
  let customShare = store.state.share.custom
  if (customShare.targetId) {
    let pageUrl = customShare.pageUrl || toRoute.fullPath
    axios.post('/wx/share/callback', {
      urlId: uuid,
      pageUrl: $qxueyou.htmlRoot + pageUrl,
      targetId: customShare.targetId,
      planIds: customShare.planIds
    }).then(() => {
      initShareOption(toRoute)
    })
  }
 
  // 当分享有方案Id,触发是否关注公众号
  if (customShare.planIds) {
    store.commit('wxh5/subscribe', '及时获取奖励提醒')
  }
 
  let mask = store.state.share.mask
  if (mask.show) {
    let text = mask.type === 'plan' ? '分享成功,继续助力' : '邀请成功,继续邀请'
    let newMask = { show: true, type: mask.type, text: text, codeText: mask.codeText }
    store.commit("share/maskText", newMask)
  }
}
 
/**
 * 统一支付接口处理
 * @param {*} orderId
 * @param {*} successCallback // 支付成功回调
 * @param {*} showCodeCallback // 显示二维码回调
 */
function unipayPay(orderId, successCallback, showCodeCallback) {
  axios.post('/wx/pay/createOrder', {
    orderId: orderId,
    channel: channel,
    redirectUrl: weixinFlag ? store.state.order.paySuccessUrl : undefined,
  }).then(res => {
    if (!res.data.data) { return false }
    
    let params = res.data.data.param
 
    if (isWxpub) { // 公众号支付
      chooseWXPay(params, successCallback)
    } else { // 扫码支付
      store.commit('timer/paying', true)
      showCodeCallback && showCodeCallback(params.codeUrl)
      checkIsPay(orderId, successCallback)
    }
  })
}
 
function chooseWXPay(result, successCallback) {
  //调用微信支付接口
  wx.chooseWXPay({
    timestamp: result.timeStamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
    nonceStr: result.nonceStr, // 支付签名随机串,不长于 32 位
    package: result.packageValue, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
    signType: result.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
    paySign: result.paySign, // 支付签名
    success: () => {
      successCallback && successCallback()
    },
    fail: (e) => {
      store.commit('snack/error', '请联系技术客服解决' + e.errMsg)
    }
  })
}
 
/**
 * 扫码支付成功的回调
 * @param {} orderId
 * @returns {} 
 */
function checkIsPay(orderId, successCallback) {
  if (!store.state.timer.paying) {
    return false
  }
  setTimeout(function () {
    axios.get('/transact/order/payResult', {
      params: { orderId: orderId }
    }).then(res => {
      if (res.data.success) {
        successCallback && successCallback()
        store.commit('timer/paying', false)
      } else {
        checkIsPay(orderId, successCallback)
      }
    })
  }, 2000)
}
 
/**
 * 获取定位
 * @param {*} locationCallback 
 */
function getPosition(locationCallback){
  wx.getLocation({
    success: function (res) {
      locationCallback(res)
    }
  })  
}
 
function chooseImage(){
  return new Promise((resolve) => {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        if (res && res.localIds) {
          getLocalImgData(res.localIds[0]).then((localData) => {
            resolve(localData)
          })
        } else {
          store.commit('snack/error', `微信上传图片失败:${res}`)
        }
      },
      fail:function(e) {
        store.commit('snack/error', `微信上传图片异常:${JSON.stringify(e)}`)
      }
    })
  })
}
function getLocalImgData(localId){
  return new Promise((resolve) => {
    wx.getLocalImgData({
      localId: localId,
      success: function (res) {
        resolve(res.localData)
      },
      fail:function(e) {
        store.commit('snack/error', `微信获取图片异常:${JSON.stringify(e)}`)
      }
    })
  })
}
 
 
/**
 * 预览图片
 * @param {*} url 
 * @param {*} urlList 
 */
function previewImage(current, urls){
  wx.previewImage({
    current: current, // 当前显示图片的http链接
    urls: urls ? urls : [current] // 需要预览的图片http链接列表
  })
}
 
/**
 * 返回小程序页面
 * @param {*} mpRouter // 小程序的路由
 * @param {*} otherCallback // 其他回调操作
 */
function redirectToMp(mpRouter) {
  return new Promise(resolve => {
    // 非微信 或 人社局活动入口
    if (!weixinFlag || store.state.course.isRsjActivity) {
      resolve(true)
      return false
    }
    wx.miniProgram.getEnv(function(res) {
      if (res.miniprogram) { // 小程序
        wx.miniProgram.redirectTo({
          url: mpRouter,
          success: function(){
            console.log('跳转成功')
            setTimeout(() => { // 处理其他机构的小程序跳转场景
              resolve(true);
            }, 3000)
          },
          fail: function(){
            resolve(true)
          }
        })
      } else { // 非小程序
        resolve(true)
      }
    })
  })
}
 
/**
 * 向小程序发送消息
 */
function postMessage(data) {
  // 非微信
  if (!weixinFlag) { return false }
 
  wx.miniProgram.getEnv(function(res) {
    if (res.miniprogram) { // 小程序
      wx.miniProgram.postMessage({
        data: data
      })
    }
  })
}
 
export {
  getWxSignature,
  initShareOption,
  unipayPay,
  getPosition,
  previewImage,
  chooseImage,
  redirectToMp,
  postMessage
}