Files
xk-doctor-wx/common/js/wx-bind-helper.js
2026-07-13 12:52:36 +08:00

95 lines
2.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 医生端微信绑定辅助方法
* 供 wx-bind-entry 与内容安全自动绑定复用,避免重复 uni.login + bind 逻辑
*/
import { bindDoctorWxWechat } from '@/api/doctorAuth.js';
/**
* 调用 uni.login 获取微信 code
* @returns {Promise<string>}
*/
function getWxLoginCode() {
return new Promise((resolve, reject) => {
// #ifdef MP-WEIXIN
uni.login({
provider: 'weixin',
success: (loginRes) => {
if (!loginRes.code) {
reject({ msg: '获取微信授权失败' });
return;
}
resolve(loginRes.code);
},
fail: () => reject({ msg: '微信授权失败' }),
});
// #endif
// #ifndef MP-WEIXIN
reject({ msg: '请在微信小程序中使用' });
// #endif
});
}
/**
* 确保当前医生账号已绑定微信 openid(内容安全等接口依赖)
* @param {Object} options
* @param {boolean} options.showLoading 是否展示 loading,组件内已有 loading 时可传 false
* @returns {Promise<boolean>} 绑定成功返回 true
*/
export async function ensureDoctorWxBound(options = {}) {
const { showLoading = true } = options;
if (showLoading) {
uni.showLoading({ title: '绑定中...', mask: true });
}
try {
const code = await getWxLoginCode();
const { ok, res } = await bindDoctorWxWechat(code);
if (!ok) {
throw {
msg: (res && (res.message || res.msg)) || '绑定失败,请前往「我的 → 绑定微信」手动绑定',
};
}
return true;
} finally {
if (showLoading) {
uni.hideLoading();
}
}
}
/**
* 弹出确认框,用户同意后再绑定微信(内容安全等被动触发场景使用)
* @param {Object} options
* @param {string} options.title 弹窗标题
* @param {string} options.content 弹窗正文
* @param {boolean} options.showLoading 绑定过程是否展示 loading
* @returns {Promise<boolean>} 绑定成功返回 true,用户取消返回 false
*/
export function promptDoctorWxBind(options = {}) {
const {
title = '提示',
content = '内容安全校验需要绑定微信,是否立即绑定?',
showLoading = true,
} = options;
return new Promise((resolve, reject) => {
uni.showModal({
title,
content,
confirmText: '去绑定',
cancelText: '取消',
success: async (res) => {
if (!res.confirm) {
resolve(false);
return;
}
try {
await ensureDoctorWxBound({ showLoading });
resolve(true);
} catch (e) {
reject(e);
}
},
fail: () => resolve(false),
});
});
}