Vue3 uniapp h5微信好友分享 微信支付(集成JSSDK)

1,228 阅读2分钟

1.首页引入weixin-js-sdk

npm i weixin-js-sdk --save

2.微信分享和微信支付方法的封装

import wx from 'weixin-js-sdk'
import {wechatPay, wechatShare} from '@/api/business.js'


// 微信支付(微信支付V3)
export const wechatPayJs = async (prepay, callback, errorCallback) => {
  if (!window.WeixinJSBridge) {
    uni.showToast({icon: 'none', title: '请在微信中打开', duration: 2000});
    return;
  }
  let result = await wechatPay(prepay);  //获取参数
  if (result.code !== 200) {
    uni.showToast({icon: 'none', title: result.msg || '签名失败', duration: 2000});
    return;
  }
  let {appId, timestamp, nonceStr, signature, prepayId} = result.data;
  WeixinJSBridge.invoke('getBrandWCPayRequest', {
    "appId": appId,
    "timeStamp": timestamp,
    "nonceStr": nonceStr,
    "package": prepayId,
    "signType": "RSA",
    "paySign": signature
  }, (res) => {
    //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
    switch (res.err_msg) {
      case "get_brand_wcpay_request:ok":
        callback && callback("支付成功");
        break;
      case "get_brand_wcpay_request:cancel":
        errorCallback && errorCallback("你已经取消支付了");
        break;
      case "get_brand_wcpay_request:fail":
      default:
        errorCallback && errorCallback("支付失败了");
    }
  })
}


// 微信分享
// link拼接:window.location.origin + window.location.pathname + '自定义参数' 
export const wechatShare = async (url, link) => {
  let result = await wechatShare(url);  //获取参数接口
  if (result.code !== 200) {
    uni.showToast({icon: 'none', title: result.msg || '签名失败', duration: 2000});
    return;
  }
  wechatShareConfig(result.data, {
    title: '自定义', desc: '自定义', link:'自定义', imgUrl:'自定义,可以使用网络图片地址'
  });
  //项目中图片地址: location.origin + location.pathname + 'logo.png'
  //图片网络地址:自定义
}
// 微信分享配置
export const wechatShareConfig = ({appId, timestamp, nonceStr, signature}, {title, link, imgUrl, desc}) => {
  wx.config({
    debug: false,
    appId: appId,
    timestamp: timestamp,
    nonceStr: nonceStr,
    signature: signature,
    jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
  });
  wx.checkJsApi({
    jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData'],
    success: (res) => console.log(res, 'checkJsApi')
  });
  wx.ready(function () {
    // //分享到朋友圈”及“分享到QQ空间”
    wx.updateTimelineShareData({title, link, imgUrl, success: (res) => console.log("分享朋友圈成功返回的信息为:", res)})
    //“分享给朋友”及“分享到QQ”
    wx.updateAppMessageShareData({title, desc, link, imgUrl, success: (res) => console.log("分享朋友成功返回的信息为:", res)})
  });
  wx.error((res) => console.log('验证失败返回的信息:', res));
}

3.获取签名、随机数、时间戳的url

url:encodeURIComponent(window.location.href.split('#')[0])

4.踩坑 签名失败:(这个是最棘手的问题,我希望你能避坑)

- window.location.href.split('#')[0] 截取之后的 / 必须保存,不能去除,否则会报签名失败 
- encodeURIComponent(window.location.href.split('#')[0]) 必须加密
- 其他情况文档说明

5.集成文档

JSSDK:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#1
支付:<https://pay.weixin.qq.com/wiki/doc/apiv3/index.shtml>