99 lines
2.7 KiB
JavaScript
99 lines
2.7 KiB
JavaScript
/**
|
||
* 小程序服务层
|
||
* 提供 H5 跳转小程序相关的 API 调用
|
||
*/
|
||
import axios from 'axios';
|
||
import { getApiBase } from '@utils/apiConfig';
|
||
|
||
const api = axios.create({
|
||
baseURL: getApiBase(),
|
||
timeout: 30000, // 增加到 30 秒,因为首次需要从微信 API 获取 access_token 和 jsapi_ticket
|
||
withCredentials: true,
|
||
});
|
||
|
||
/**
|
||
* 获取微信 JS-SDK 签名配置
|
||
* 用于在微信内 H5 使用开放标签 wx-open-launch-weapp
|
||
*
|
||
* @param {string} url - 当前页面 URL(会自动移除 hash 部分)
|
||
* @returns {Promise<Object>} 签名配置对象
|
||
*/
|
||
export const getJsSdkConfig = async (url) => {
|
||
try {
|
||
const response = await api.post('/api/wechat/jssdk-config', { url });
|
||
|
||
if (response.data.code === 200) {
|
||
return response.data.data;
|
||
}
|
||
|
||
throw new Error(response.data.message || '获取签名配置失败');
|
||
} catch (error) {
|
||
console.error('[miniprogramService] getJsSdkConfig error:', error);
|
||
throw error;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 生成小程序 URL Scheme
|
||
* 用于外部浏览器拉起微信打开小程序
|
||
*
|
||
* @param {Object} options - 配置选项
|
||
* @param {string} [options.path] - 小程序页面路径,如 /pages/index/index
|
||
* @param {string} [options.query] - 页面参数,如 id=123&from=h5
|
||
* @param {number} [options.expireInterval=30] - 有效天数,最长 30 天
|
||
* @returns {Promise<Object>} 包含 openlink 的对象
|
||
*/
|
||
export const generateUrlScheme = async (options = {}) => {
|
||
try {
|
||
const { path, query, expireInterval = 30 } = options;
|
||
|
||
const response = await api.post('/api/miniprogram/url-scheme', {
|
||
path,
|
||
query,
|
||
expire_type: 1,
|
||
expire_interval: expireInterval,
|
||
});
|
||
|
||
if (response.data.code === 200) {
|
||
return response.data.data;
|
||
}
|
||
|
||
throw new Error(response.data.message || '生成 URL Scheme 失败');
|
||
} catch (error) {
|
||
console.error('[miniprogramService] generateUrlScheme error:', error);
|
||
throw error;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 打开 URL Scheme
|
||
* 尝试通过 URL Scheme 拉起微信
|
||
*
|
||
* @param {string} openlink - URL Scheme 链接
|
||
* @returns {boolean} 是否成功发起跳转
|
||
*/
|
||
export const openUrlScheme = (openlink) => {
|
||
if (!openlink) {
|
||
console.error('[miniprogramService] openUrlScheme: openlink is required');
|
||
return false;
|
||
}
|
||
|
||
try {
|
||
// 方式1:直接跳转
|
||
window.location.href = openlink;
|
||
return true;
|
||
} catch (error) {
|
||
console.error('[miniprogramService] openUrlScheme error:', error);
|
||
return false;
|
||
}
|
||
};
|
||
|
||
// 注意:getMiniprogramQRCode 功能暂未实现后端 API
|
||
// PC 端目前使用静态小程序码图片,如需动态生成请实现 /api/miniprogram/qrcode 接口
|
||
|
||
export default {
|
||
getJsSdkConfig,
|
||
generateUrlScheme,
|
||
openUrlScheme,
|
||
};
|