1、安裝jweixin-module
npm install jweixin-module --save
2、封裝jssdk存為wxShare.js
const wx = require('weixin-js-sdk'); export const weixinShare=async function(option={},func) { let ua = window.navigator.userAgent.toLowerCase(); if(!ua.match(/MicroMessenger/i) == 'micromessenger'){ return; } let res=await func("/hy.ashx",{act:"jsapi",'url':encodeURIComponent(location.href)},true); if(res.code==200) { let apiInfo=res.data; wx.config({ debug:true, appId:apiInfo.appId, timestamp:apiInfo.timestamp, nonceStr:apiInfo.nonceStr, signature:apiInfo.signature, jsApiList: ['updateAppMessageShareData','updateTimelineShareData'], fail: function () { location.reload(); } }); wx.ready(function() { let shareData={ title: option.title, // 分享標題 //desc: option.desc, // 分享描述 link:option.link.split("#")[0], // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 imgUrl:option.img!=''?option.img: 'http://xx/static/images/logo.gif', // 分享圖標 success: function (response) { console.log(response); } }; wx.updateAppMessageShareData(shareData); wx.updateTimelineShareData(shareData); }); } }
封裝ajax
getParamsRequest 為 ajax.js
const BASE_URL = "https://xx.com/api" /** * 封裝get請求 */ export const getParamsRequest = (url, params, showLoading,method="GET") => ( new Promise((resolve, reject) => { if (showLoading) { uni.showLoading({ title: '加載中' }); } let token=uni.getStorageSync('token'); uni.request({ url: `${BASE_URL}${url}`, method: method, data:params, header:{"content-type":"application/x-www-form-urlencoded","token":token}, //header:{"token":token}, dataType:"json", duration:3000, success: (res) => { let redirectUrl='index'; try { redirectUrl=/(\/pages\/[a-z_/0-9?=&]+)$/.exec(location.href)[0]; } catch(e){} if (res.statusCode == 200) { if(res.data.code==201) { uni.redirectTo({ url:'/pages/member/login?redirect='+redirectUrl }) } resolve(res.data); } else { reject("出錯了"); } }, fail: (res) => { reject("出錯了"); }, complete: () => { if (showLoading) { uni.hideLoading(); } } }) }) );
3、在頁面中使用
引入
import {getParamsRequest from "../../static/js/ajax.js"; import {weixinShare} from "../../static/js/wxShare.js";
使用:
weixinShare({title:'測試',link:location.href.split("#")[0],img:'http://xxx/test.jpg'},getParamsRequest);
4、效果
相關資料:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html