该博客内容纯属原创,引用请使用外链:

开发环境:uni-app + uni-simple-router

封装微信API及使用

1、封装微信API

  1. import { wechatConfig, wechatPayConfig, wechatShareConfig } from "wechat";
  2. import wx from "weixin-js-sdk";
  3. import { IWechatApis } from "./IWechatApis";
  4. export default class WechatApis implements IWechatApis {
  5. // 微信接口
  6. 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'];
  7. private appId: string | null = null;
  8. private readHandler: Function | null = null;
  9. /**
  10. * 构造函数,定义一个配置
  11. * @param config
  12. */
  13. constructor(config: wechatConfig) {
  14. this.appId = config.appId;
  15. wx.config({
  16. debug: JSON.parse(process.env.VUE_APP_DEBUG) || false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  17. appId: config.appId, // 必填,公众号的唯一标识
  18. timestamp: config.timestamp, // 必填,生成签名的时间戳
  19. nonceStr: config.nonceStr, // 必填,生成签名的随机串
  20. signature: config.signature,// 必填,签名,见附录1
  21. jsApiList: [...this.jsApiList, ...config.jsApiList] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
  22. });
  23. wx.ready(() => {});
  24. wx.error((error: any) => {console.log("error")});
  25. }
  26. /**
  27. * 微信支付请求
  28. * @param config 微信支付配置
  29. * @returns
  30. */
  31. public wechatPay(config: wechatPayConfig): Promise<any> {
  32. const _config: wechatPayConfig = config;
  33. _config.timestamp = (config as any).timeStamp;
  34. return this.setWechatReturn("chooseWXPay", _config);
  35. }
  36. /**
  37. * “分享给朋友”及“分享到QQ”
  38. * @param config
  39. */
  40. public wechatUpdateShareAppMessage(config: wechatShareConfig): Promise<any> {
  41. const _config: wechatShareConfig = config;
  42. return this.setWechatReturn("updateAppMessageShareData", _config);
  43. }
  44. /**
  45. * 统一配置微信接口使用方式
  46. * @param apiName 微信API 接口 名称
  47. * @param config 微信接口参数
  48. * @returns 返回 promise
  49. */
  50. private setWechatReturn(apiName: string, config: any) {
  51. const _successHandler = config?.success || null;
  52. const _cancelHandler = config?.cancel || null;
  53. const _failHandler = config?.fail || null;
  54. return new Promise((resolve, reject) => {
  55. config["success"] = (response?: any): void => {
  56. _successHandler?.(response);
  57. resolve(response);
  58. }
  59. config["cancel"] = (response?: any): void => {
  60. _cancelHandler?.(response);
  61. reject(response);
  62. }
  63. config["fail"] = (error?: any): void => {
  64. _failHandler?.(error);
  65. reject(error);
  66. }
  67. wx[apiName](config);
  68. });
  69. }
  70. }

2、从后台获取微信配置信息,并返回微信接口实例

  1. import { request } from '@/utils/request/request';
  2. import WechatApis from "./WechatApis";
  3. /**
  4. * 注入微信配置
  5. * @param url config配置url
  6. * @returns 微信接口
  7. */
  8. export const getWechatConfig = async (url: string): Promise<WechatApis> => {
  9. // 调用获取Config的接口
  10. const {data} = await request.get("api/order/wxconfig",{url});
  11. // 返回wechatApis 实例
  12. return new WechatApis(data);
  13. }

使用微信API

wechatUpdateShareAppMessage 方法为例

1、由于 uni-simple-router 插件的限制,通过App.vue 中使用以下代码修复第一次进入系统时,触发不了这个插件

  1. # App.vue
  2. <script lang="ts">
  3. import { Vue } from 'vue-property-decorator'
  4. export default Vue.extend({
  5. mpType: 'app',
  6. onLaunch() {
  7. // 第一次进入系统,由于Router插件不能拦截,由以下实现登录鉴权
  8. // iOS 用户 config 鉴权需要刷新一次,这边允许iOS 系统重新进入
  9. if(window.performance.navigation.type !== 1 || isIOS()) {
  10. // performance.navigation.type = 0 表示用户不是刷新操作(刷新操作 = 1)
  11. const query: any = {};
  12. window.location.search?.substring(1).split("&").forEach(item => {
  13. const pair = item.split("=");
  14. query[pair[0]] = pair[1];
  15. });
  16. this.$Router.replace({ path: this.$Route.fullPath, query });
  17. }
  18. console.log('App Launch')
  19. },
  20. onShow() {
  21. console.log('App Show')
  22. },
  23. onHide() {
  24. console.log('App Hide')
  25. }
  26. });
  27. </script>
  28. <style lang="scss">
  29. /*每个页面公共css */
  30. @import "./common/css/reset.scss";
  31. @import "./common/css/common.scss";
  32. @import "./common/fonts/iconfont.scss";
  33. </style>

2、在 router.afterEach 方法中使用以下代码实现配置

  1. // 用于在页面中获取微信接口实例
  2. router.$wechatApis = null;
  3. router.afterEach((to, from) => {
  4. // isSDK 页面是否需要微信配置
  5. const { isSDK } = to.meta as any;
  6. const path = location.origin + to.fullPath;
  7. if(router.$wechatApis === null) {
  8. getWechatConfig(path).then(wechatApis => {
  9. router.$wechatApis = wechatApis;
  10. // IOS 系统需要刷新页面---后续发现ios不需要(????)
  11. // if(window.performance.navigation.type !== 1 && isIOS()) {
  12. // // performance.navigation.type = 0 表示用户不是刷新操作(刷新操作 = 1)
  13. // window.location.reload();
  14. //}
  15. });
  16. }
  17. });

3、在页面中使用

  1. public onHShareAppMessage() {
  2. // 微信配置config
  3. this.$Router.$wechatApis?.wechatUpdateShareAppMessage({
  4. title: "process.env.VUE_APP_NAME", // 分享标题
  5. desc: '这是一个公众号程序', // 分享描述
  6. link: window.location.origin, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  7. imgUrl: 'http://www.hccollege.cn/upload/teacherpic/20200310/aca8ea050114f839f9fc48fec5640a7f.jpg', // 分享图标
  8. }).then(() => {
  9. // 分享成功
  10. }).catch(() => {
  11. // 分享失败
  12. });
  13. }