该博客内容纯属原创,引用请使用外链:
开发环境:uni-app + uni-simple-router
封装微信API及使用
1、封装微信API
import { wechatConfig, wechatPayConfig, wechatShareConfig } from "wechat";import wx from "weixin-js-sdk";import { IWechatApis } from "./IWechatApis";export default class WechatApis implements IWechatApis {// 微信接口private jsApiList = ['updateAppMessageShareData', 'updateTimelineShareData', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'];private appId: string | null = null;private readHandler: Function | null = null;/*** 构造函数,定义一个配置* @param config*/constructor(config: wechatConfig) {this.appId = config.appId;wx.config({debug: JSON.parse(process.env.VUE_APP_DEBUG) || false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。appId: config.appId, // 必填,公众号的唯一标识timestamp: config.timestamp, // 必填,生成签名的时间戳nonceStr: config.nonceStr, // 必填,生成签名的随机串signature: config.signature,// 必填,签名,见附录1jsApiList: [...this.jsApiList, ...config.jsApiList] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2});wx.ready(() => {});wx.error((error: any) => {console.log("error")});}/*** 微信支付请求* @param config 微信支付配置* @returns*/public wechatPay(config: wechatPayConfig): Promise<any> {const _config: wechatPayConfig = config;_config.timestamp = (config as any).timeStamp;return this.setWechatReturn("chooseWXPay", _config);}/*** “分享给朋友”及“分享到QQ”* @param config*/public wechatUpdateShareAppMessage(config: wechatShareConfig): Promise<any> {const _config: wechatShareConfig = config;return this.setWechatReturn("updateAppMessageShareData", _config);}/*** 统一配置微信接口使用方式* @param apiName 微信API 接口 名称* @param config 微信接口参数* @returns 返回 promise*/private setWechatReturn(apiName: string, config: any) {const _successHandler = config?.success || null;const _cancelHandler = config?.cancel || null;const _failHandler = config?.fail || null;return new Promise((resolve, reject) => {config["success"] = (response?: any): void => {_successHandler?.(response);resolve(response);}config["cancel"] = (response?: any): void => {_cancelHandler?.(response);reject(response);}config["fail"] = (error?: any): void => {_failHandler?.(error);reject(error);}wx[apiName](config);});}}
2、从后台获取微信配置信息,并返回微信接口实例
import { request } from '@/utils/request/request';import WechatApis from "./WechatApis";/*** 注入微信配置* @param url config配置url* @returns 微信接口*/export const getWechatConfig = async (url: string): Promise<WechatApis> => {// 调用获取Config的接口const {data} = await request.get("api/order/wxconfig",{url});// 返回wechatApis 实例return new WechatApis(data);}
使用微信API
以 wechatUpdateShareAppMessage 方法为例
1、由于 uni-simple-router 插件的限制,通过App.vue 中使用以下代码修复第一次进入系统时,触发不了这个插件
# App.vue<script lang="ts">import { Vue } from 'vue-property-decorator'export default Vue.extend({mpType: 'app',onLaunch() {// 第一次进入系统,由于Router插件不能拦截,由以下实现登录鉴权// iOS 用户 config 鉴权需要刷新一次,这边允许iOS 系统重新进入if(window.performance.navigation.type !== 1 || isIOS()) {// performance.navigation.type = 0 表示用户不是刷新操作(刷新操作 = 1)const query: any = {};window.location.search?.substring(1).split("&").forEach(item => {const pair = item.split("=");query[pair[0]] = pair[1];});this.$Router.replace({ path: this.$Route.fullPath, query });}console.log('App Launch')},onShow() {console.log('App Show')},onHide() {console.log('App Hide')}});</script><style lang="scss">/*每个页面公共css */@import "./common/css/reset.scss";@import "./common/css/common.scss";@import "./common/fonts/iconfont.scss";</style>
2、在 router.afterEach 方法中使用以下代码实现配置
// 用于在页面中获取微信接口实例router.$wechatApis = null;router.afterEach((to, from) => {// isSDK 页面是否需要微信配置const { isSDK } = to.meta as any;const path = location.origin + to.fullPath;if(router.$wechatApis === null) {getWechatConfig(path).then(wechatApis => {router.$wechatApis = wechatApis;// IOS 系统需要刷新页面---后续发现ios不需要(????)// if(window.performance.navigation.type !== 1 && isIOS()) {// // performance.navigation.type = 0 表示用户不是刷新操作(刷新操作 = 1)// window.location.reload();//}});}});
3、在页面中使用
public onHShareAppMessage() {// 微信配置configthis.$Router.$wechatApis?.wechatUpdateShareAppMessage({title: "process.env.VUE_APP_NAME", // 分享标题desc: '这是一个公众号程序', // 分享描述link: window.location.origin, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致imgUrl: 'http://www.hccollege.cn/upload/teacherpic/20200310/aca8ea050114f839f9fc48fec5640a7f.jpg', // 分享图标}).then(() => {// 分享成功}).catch(() => {// 分享失败});}
