Browse Source

修改微信支付无法使用的问题

zyh
Gao xiaosong 4 years ago
parent
commit
1cf7f78b7c
  1. 323
      libs/wechat.js

323
libs/wechat.js

@ -1,36 +1,39 @@
import { subscribeMessage } from "@/libs/order"; import { subscribeMessage } from '@/libs/order'
import { getProvider } from "@/utils"; import { getProvider } from '@/utils'
import WechatJSSDK from "wechat-jssdk/dist/client.umd"; import WechatJSSDK from 'wechat-jssdk/dist/client.umd'
import { getWechatConfig, wechatAuth } from "@/api/public"; import { getWechatConfig, wechatAuth } from '@/api/public'
import { parseQuery } from "@/utils"; import { parseQuery } from '@/utils'
import cookie from "@/utils/store/cookie"; import cookie from '@/utils/store/cookie'
import store from "@/store"; import store from '@/store'
import dayjs from "dayjs"; import dayjs from 'dayjs'
// 支付模块 // 支付模块
export const weappPay = (option) => { export const weappPay = option => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (store.state.$deviceType == 'weixinh5') { if (store.state.$deviceType == 'weixinh5') {
setTimeout(() => { setTimeout(() => {
location.href = option.mweb_url; location.href = option.mweb_url
}, 100); }, 100)
resolve() resolve()
return return
} }
if (store.state.$deviceType == 'weixin') { if (store.state.$deviceType == 'weixin') {
pay(option).then(() => { pay(option)
.then(() => {
uni.showToast({ uni.showToast({
title: '支付成功', icon: 'success', duration: 5000, title: '支付成功',
}); icon: 'success',
duration: 5000,
})
resolve() resolve()
}) })
.finally(res => { .finally(res => {
//if(typeof(res) == "undefined") return //if(typeof(res) == "undefined") return
}) })
.catch(function () { .catch(function() {
uni.showToast({ title: '支付失败', icon: 'none', duration: 5000 }); uni.showToast({ title: '支付失败', icon: 'none', duration: 5000 })
reject() reject()
}); })
return return
} }
// 吊起微信支付 // 吊起微信支付
@ -48,13 +51,15 @@ export const weappPay = (option) => {
uni.requestPayment({ uni.requestPayment({
provider: 'wxpay', provider: 'wxpay',
...option, ...option,
timestamp: orderInfo.timestamp, timeStamp: orderInfo.timestamp,
orderInfo, orderInfo,
success: (success) => { success: success => {
console.log(success) console.log(success)
uni.showToast({ uni.showToast({
title: '支付成功', icon: 'success', duration: 5000, title: '支付成功',
}); icon: 'success',
duration: 5000,
})
let time = setTimeout(() => { let time = setTimeout(() => {
clearTimeout(time) clearTimeout(time)
resolve(success) resolve(success)
@ -63,28 +68,26 @@ export const weappPay = (option) => {
subscribeMessage() subscribeMessage()
// #endif // #endif
}, },
fail: (error) => { fail: error => {
console.log(error) console.log(error)
if (error.errMsg == 'requestPayment:fail cancel') { if (error.errMsg == 'requestPayment:fail cancel') {
uni.showToast({ title: '已取消支付', icon: 'none', duration: 5000 }); uni.showToast({ title: '已取消支付', icon: 'none', duration: 5000 })
} else { } else {
uni.showToast({ title: error || error.msg, icon: 'none', duration: 5000 }); uni.showToast({ title: error || error.msg, icon: 'none', duration: 5000 })
} }
reject(error) reject(error)
} },
}) })
// }) // })
}) })
} }
const STATE_KEY = 'wx_authorize_state'
const WX_AUTH = 'wx_auth'
const STATE_KEY = "wx_authorize_state"; const BACK_URL = 'login_back_url'
const WX_AUTH = "wx_auth"; const LOGINTYPE = 'loginType'
const BACK_URL = "login_back_url"; let instance
const LOGINTYPE = "loginType"; let wechatObj
let instance;
let wechatObj;
let appId let appId
let wechatLoading = false let wechatLoading = false
@ -92,41 +95,41 @@ export function wechat() {
console.log('初始化微信配置') console.log('初始化微信配置')
wechatLoading = false wechatLoading = false
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (instance) return resolve(instance); if (instance) return resolve(instance)
getWechatConfig() getWechatConfig()
.then(res => { .then(res => {
console.log(res.data) console.log(res.data)
const _wx = WechatJSSDK(res.data); const _wx = WechatJSSDK(res.data)
console.log(_wx) console.log(_wx)
appId = res.data.appId appId = res.data.appId
wechatObj = _wx; wechatObj = _wx
_wx _wx
.initialize() .initialize()
.then(() => { .then(() => {
instance = _wx.wx; instance = _wx.wx
instance.initConfig = res.data; instance.initConfig = res.data
resolve(instance); resolve(instance)
}) })
.catch(error => { .catch(error => {
console.log(error) console.log(error)
uni.showToast({ uni.showToast({
title: error, title: error,
icon: "none", icon: 'none',
duration: 2000 duration: 2000,
}); })
reject() reject()
}); })
}) })
.catch(err => { .catch(err => {
console.log(err); console.log(err)
reject(); reject()
}); })
}); })
} }
export function clearAuthStatus() { export function clearAuthStatus() {
cookie.remove(WX_AUTH); cookie.remove(WX_AUTH)
cookie.remove(STATE_KEY); cookie.remove(STATE_KEY)
} }
export async function oAuth() { export async function oAuth() {
@ -137,11 +140,11 @@ export async function oAuth() {
// if (cookie.has(WX_AUTH)) { // if (cookie.has(WX_AUTH)) {
if (cookie.has(WX_AUTH) && store.state.token) { if (cookie.has(WX_AUTH) && store.state.token) {
reject() reject()
return; return
} }
const { code } = parseQuery(); const { code } = parseQuery()
if (!code) { if (!code) {
toAuth(); toAuth()
return return
} else { } else {
auth(code) auth(code)
@ -155,24 +158,24 @@ export async function oAuth() {
export async function auth(code) { export async function auth(code) {
console.log('获取微信授权') console.log('获取微信授权')
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let loginType = cookie.get(LOGINTYPE); let loginType = cookie.get(LOGINTYPE)
let spread = cookie.get('spread'); let spread = cookie.get('spread')
console.log('微信授权登录前获取spread', spread) console.log('微信授权登录前获取spread', spread)
wechatAuth(code, spread, loginType) wechatAuth(code, spread, loginType)
.then(({ data }) => { .then(({ data }) => {
console.log(data) console.log(data)
const expires_time = dayjs(data.expires_time); const expires_time = dayjs(data.expires_time)
const newTime = Math.round(new Date() / 1000); const newTime = Math.round(new Date() / 1000)
store.commit("login", data.token, expires_time - newTime); store.commit('login', data.token, expires_time - newTime)
cookie.set(WX_AUTH, code, expires_time); cookie.set(WX_AUTH, code, expires_time)
cookie.remove(STATE_KEY); cookie.remove(STATE_KEY)
loginType && cookie.remove(LOGINTYPE); loginType && cookie.remove(LOGINTYPE)
console.log('微信公众号授权登录,获取用户信息') console.log('微信公众号授权登录,获取用户信息')
store.dispatch('getUser').finally(() => { store.dispatch('getUser').finally(() => {
resolve(); resolve()
}) })
}) })
.catch(reject); .catch(reject)
}).catch(error => { }).catch(error => {
console.log(error) console.log(error)
}) })
@ -184,27 +187,26 @@ export async function toAuth() {
} }
wechatLoading = true wechatLoading = true
wechat().then(wx => { wechat().then(wx => {
location.href = getAuthUrl(appId); location.href = getAuthUrl(appId)
}); })
} }
function getAuthUrl(appId) { function getAuthUrl(appId) {
// const redirect_uri = encodeURIComponent(window.location.href); // const redirect_uri = encodeURIComponent(window.location.href);
// const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index`); // const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index`);
// #ifdef H5 // #ifdef H5
// #endif // #endif
cookie.set('redirect', window.location.href) cookie.set('redirect', window.location.href)
const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index`); const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index`)
// const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index?path=${encodeURIComponent(window.location.href)}`); // const redirect_uri = encodeURIComponent(`${location.origin}/pages/Loading/index?path=${encodeURIComponent(window.location.href)}`);
// const redirect_uri = encodeURIComponent(`${window.location.origin}${window.location.pathname}`) // const redirect_uri = encodeURIComponent(`${window.location.origin}${window.location.pathname}`)
// const redirect_uri = encodeURIComponent(`${location.origin}`) // const redirect_uri = encodeURIComponent(`${location.origin}`)
cookie.remove(BACK_URL); cookie.remove(BACK_URL)
const state = 'STATE' const state = 'STATE'
// const state = encodeURIComponent(("" + Math.random()).split(".")[1] + "authorizestate"); // const state = encodeURIComponent(("" + Math.random()).split(".")[1] + "authorizestate");
cookie.set(STATE_KEY, state); cookie.set(STATE_KEY, state)
return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`; return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
} }
function toPromise(fn, config = {}) { function toPromise(fn, config = {}) {
@ -212,185 +214,184 @@ function toPromise(fn, config = {}) {
fn({ fn({
...config, ...config,
success(res) { success(res) {
resolve(res); resolve(res)
}, },
fail(err) { fail(err) {
reject(err); reject(err)
}, },
complete(err) { complete(err) {
reject(err); reject(err)
}, },
cancel(err) { cancel(err) {
reject(err); reject(err)
} },
}); })
}); })
} }
export function pay(config) { export function pay(config) {
console.log(instance) console.log(instance)
return toPromise(instance.chooseWXPay, config); return toPromise(instance.chooseWXPay, config)
} }
export function openAddress() { export function openAddress() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
wechatEvevt("openAddress", {}) wechatEvevt('openAddress', {})
.then(res => { .then(res => {
resolve(res); resolve(res)
}) })
.catch(res => { .catch(res => {
if (res.is_ready) { if (res.is_ready) {
res.wx.openAddress({ res.wx.openAddress({
fail(res) { fail(res) {
reject(res); reject(res)
}, },
success(res) { success(res) {
resolve(res); resolve(res)
} },
}); })
} else { } else {
reject(res); reject(res)
} }
}); })
}); })
} }
export function openShareAll(config) { export function openShareAll(config) {
config || {}; config || {}
config.type = config.type == undefined ? "link" : config.type; config.type = config.type == undefined ? 'link' : config.type
return new Promise(resolve => { return new Promise(resolve => {
getWechatConfig().then(res => { getWechatConfig().then(res => {
wechatObj.signSignature({ wechatObj.signSignature({
nonceStr: res.data.nonceStr, nonceStr: res.data.nonceStr,
signature: res.data.signature, signature: res.data.signature,
timestamp: res.data.timestamp timestamp: res.data.timestamp,
}); })
instance = wechatObj.getOriginalWx(); instance = wechatObj.getOriginalWx()
instance.ready(() => { instance.ready(() => {
instance.updateAppMessageShareData(config); instance.updateAppMessageShareData(config)
instance.updateTimelineShareData(config); instance.updateTimelineShareData(config)
resolve(); resolve()
}); })
}); })
}); })
} }
export function openShareAppMessage(config) { export function openShareAppMessage(config) {
instance.updateAppMessageShareData(config); instance.updateAppMessageShareData(config)
instance.onMenuShareAppMessage && instance.onMenuShareAppMessage(config); instance.onMenuShareAppMessage && instance.onMenuShareAppMessage(config)
} }
export function openShareTimeline(config) { export function openShareTimeline(config) {
instance.updateTimelineShareData(config); instance.updateTimelineShareData(config)
instance.onMenuShareTimeline && instance.onMenuShareTimeline(config); instance.onMenuShareTimeline && instance.onMenuShareTimeline(config)
} }
export function wechatEvevt(name, config) { export function wechatEvevt(name, config) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let wx; let wx
let configDefault = { let configDefault = {
fail(res) { fail(res) {
if (wx) return reject({ is_ready: true, wx: wx }); if (wx) return reject({ is_ready: true, wx: wx })
getWechatConfig().then(res => { getWechatConfig().then(res => {
wechatObj.signSignature({ wechatObj.signSignature({
nonceStr: res.data.nonceStr, nonceStr: res.data.nonceStr,
signature: res.data.signature, signature: res.data.signature,
timestamp: res.data.timestamp timestamp: res.data.timestamp,
}); })
wx = wechatObj.getOriginalWx(); wx = wechatObj.getOriginalWx()
reject({ is_ready: true, wx: wx }); reject({ is_ready: true, wx: wx })
}); })
}, },
success(res) { success(res) {
resolve(res); resolve(res)
},
} }
}; Object.assign(configDefault, config)
Object.assign(configDefault, config); if (typeof instance !== 'undefined') {
if (typeof instance !== "undefined") {
instance.ready(() => { instance.ready(() => {
if (typeof name === "object") { if (typeof name === 'object') {
name.forEach(item => { name.forEach(item => {
instance[item] && instance[item](configDefault); instance[item] && instance[item](configDefault)
}); })
} else instance[name] && instance[name](configDefault); } else instance[name] && instance[name](configDefault)
}); })
} else { } else {
getWechatConfig().then(res => { getWechatConfig().then(res => {
const _wx = WechatJSSDK(res.data); const _wx = WechatJSSDK(res.data)
_wx.initialize().then(() => { _wx.initialize().then(() => {
instance = _wx.getOriginalWx(); instance = _wx.getOriginalWx()
instance.ready(() => { instance.ready(() => {
if (typeof name === "object") { if (typeof name === 'object') {
name.forEach(item => { name.forEach(item => {
instance[item] && instance[item](configDefault); instance[item] && instance[item](configDefault)
}); })
} else instance[name] && instance[name](configDefault); } else instance[name] && instance[name](configDefault)
}); })
}); })
}); })
} }
}); })
} }
export function ready() { export function ready() {
return new Promise(resolve => { return new Promise(resolve => {
if (typeof instance !== "undefined") { if (typeof instance !== 'undefined') {
instance.ready(() => { instance.ready(() => {
resolve(instance); resolve(instance)
}); })
} else { } else {
getWechatConfig().then(res => { getWechatConfig().then(res => {
const _wx = WechatJSSDK(res.data); const _wx = WechatJSSDK(res.data)
_wx.initialize().then(() => { _wx.initialize().then(() => {
instance = _wx.wx; instance = _wx.wx
instance.ready(() => { instance.ready(() => {
resolve(instance); resolve(instance)
}); })
}); })
}); })
} }
}); })
} }
export function wxShowLocation() { export function wxShowLocation() {
return new Promise(() => { return new Promise(() => {
wechatEvevt("getLocation", { type: "wgs84" }) wechatEvevt('getLocation', { type: 'wgs84' })
.then(res => { .then(res => {
let latitude = res.latitude; // 纬度 let latitude = res.latitude // 纬度
let longitude = res.longitude; // 经度 let longitude = res.longitude // 经度
cookie.set(LATITUDE, latitude); cookie.set(LATITUDE, latitude)
cookie.set(LONGITUDE, longitude); cookie.set(LONGITUDE, longitude)
}) })
.catch(res => { .catch(res => {
if (res.is_ready) { if (res.is_ready) {
res.wx.getLocation({ res.wx.getLocation({
success(res) { success(res) {
let latitude = res.latitude; // 纬度 let latitude = res.latitude // 纬度
let longitude = res.longitude; // 经度 let longitude = res.longitude // 经度
cookie.set(LATITUDE, latitude); cookie.set(LATITUDE, latitude)
cookie.set(LONGITUDE, longitude); cookie.set(LONGITUDE, longitude)
}, },
cancel() { cancel() {
cookie.remove(LATITUDE); cookie.remove(LATITUDE)
cookie.remove(LONGITUDE); cookie.remove(LONGITUDE)
uni.showToast({ uni.showToast({
title: "取消获取位置", title: '取消获取位置',
icon: "none", icon: 'none',
duration: 2000, duration: 2000,
}); })
}, },
fail() { fail() {
cookie.remove(LATITUDE); cookie.remove(LATITUDE)
cookie.remove(LONGITUDE); cookie.remove(LONGITUDE)
uni.showToast({ uni.showToast({
title: "授权失败", title: '授权失败',
icon: "none", icon: 'none',
duration: 2000, duration: 2000,
}); })
} },
}); })
} }
}); })
}); })
} }

Loading…
Cancel
Save