123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- let APPID = '';
- const isDev = false
-
- const API_BASE="http://127.0.0.1:9087"
-
-
- /**
- * 获取 code
- * @returns
- */
- export function getCode () {
- if (isDev) return '123';
-
- const matched = /[?&]*code=([^&]+)/.exec(location.search)
- if (matched) {
- return decodeURIComponent(matched[1])
- }
- }
-
- /**
- * 跳转授权页面
- */
- export function redirect () {
- if (isDev) return;
-
- const appid = APPID || 'wxd3bab568bc42d1de';
- const local = encodeURIComponent(location.origin + location.pathname)
- const scope = 'snsapi_userinfo'; // snsapi_base
- const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=${scope}&state=123#wechat_redirect`
- window.location.href = url;
- }
- function wxsdk() {
- // API_BASE 来源 public/config.js
- const apiBase = API_BASE // import.meta.env.VITE_APP_API_BASE
-
- // 分享接口
- const shareAPIs = [
- // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容(1.4.0)
- 'updateAppMessageShareData',
- // 自定义“分享到朋友圈”及“分享到 QQ 空间”按钮的分享内容(1.4.0)
- 'updateTimelineShareData',
- // 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口(即将废弃)
- 'onMenuShareTimeline',
- // 获取“分享给朋友”按钮点击状态及自定义分享内容接口(即将废弃)
- 'onMenuShareAppMessage',
- // 获取“分享到QQ”按钮点击状态及自定义分享内容接口(即将废弃)
- 'onMenuShareQQ',
- // 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
- 'onMenuShareWeibo',
- // 获取“分享到 QQ 空间”按钮点击状态及自定义分享内容接口(即将废弃)
- 'onMenuShareQZone',
- ]
-
- let inited = false;
-
- function init() {
- if (isDev) return;
- const url = window.location.href;
-
- // 请求后台接口
- fetch(`${apiBase}/api/wx/jsapi?url=${encodeURIComponent(url)}`).then(res => res.json()).then((res) => {
- if (res.code === 1000) {
- const data = res.data;
-
- APPID = data.appId;
-
- wx.config({
- debug: isDev, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来,若要查看传入的参数,可以在 pc 端打开,参数信息会通过 log 打出,仅在 pc 端时才会打印。
- appId: data.appId, // 必填,公众号的唯一标识
- timestamp: data.timestamp, // 必填,生成签名的时间戳
- nonceStr: data.nonceStr, // 必填,生成签名的随机串
- signature: data.signature,// 必填,签名
- jsApiList: [
- ...shareAPIs,
- 'openLocation',
- ] // 必填,需要使用的 JS 接口列表
- });
- }
- })
- }
-
- function share(params = {}) {
- if (isDev) return;
-
- if (!inited) {
- init();
- }
-
- wx.ready(() => {
-
- const shareData = {
- ...shareOptTpl,
- ...params
- }
-
- console.log('---分享参数-->', shareData);
-
- for (let api of shareAPIs) {
- wx[api]({
- ...shareData,
- success: () => {
- console.log('分享成功: ', api)
- },
- });
- }
- });
-
- wx.error(function(res){
- console.error('wx js-sdk error');
- console.error(res);
- console.error('<==============');
- });
- }
-
- return {
- share,
- getCode,
- redirect,
- }
- }
- export default wxsdk;
|