小程序代码:
<web-view id="myWebview" src="{{finalUrl}}" bindmessage="onWebViewMessage" binderror="onWebViewError" bindload="onWebViewLoad">
</web-view>
finalUrl="https://xxxx.xxx.xxx:34010/systemApp"
getLogin() {
console.log("获取登录code");
// 登录
wx.login({
success: res => {
console.log("获取到登录code:", res.code);
if (res.code) {
this.setData({
loginCode: res.code
});
finalUrl =this.finalUrl+ `?code=${encodeURIComponent(code)}`;
this.setData({
finalUrl: finalUrl,
});
}
},
fail: err => {
console.error('登录失败:', err);
}
})
},
uniAPP代码:
export const getCode = async () => {
console.log("进来了getCode")
let currentUrl = window.location.href;
let decodedUrl = decodeURIComponent(currentUrl);
console.log("decodedUrl===" + decodedUrl);
let url = new URL(decodedUrl);
let code = url.searchParams.get("code");
console.log("code===" + code);
getSignature();
if (code) {
getHttpOpenid(code)
} else {
storage.set("openid", '');
}
}
const getHttpOpenid = async (code: string) => {
const result: any = await openid(code);
if (result.code === 200) {
console.log("+++++++++++++++")
storage.set("openid", result.data.openid);
} else {
storage.set("openid", '');
}
}
const getSignature = async () => {
const pageUrl = window.location.origin;
console.log("pageUrl===" + pageUrl);
const result: any = await signature(pageUrl);
if (result.code === 200) {
console.log("+++++++++++++++")
getWXConfig(result.data);
} else {
storage.set("wxSDK", "");
}
}
const getWXConfig = async (data: any) => {
wx.config({
debug: true,
appId: data.appId, // 必填,公众号的唯一标识
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature, // 必填,签名
jsApiList: ["getLocation"], // 必填,需要使用的JS接口列表
});
wx.ready(() => {
// wx API 调用
console.log("wx SDK 初始化成功");
storage.set("wxSDK", "1");
});
wx.error((res) => {
console.log("wx SDK 初始化失败:", res);
storage.set("wxSDK", "");
});
};
JS接口安全域名可以填https://xxxx.xxx.xxx吗,这样写wx SDK 初始化会成功吗
1 个回复
Ask小助手 - Ask社区AI助手
在 uni-app 中给 H5 页面(最终会被嵌到微信小程序的
<web-view>里)使用 weixin-js-sdk,必须同时满足下面 3 件事,缺一不可:业务域名必须加到「JS 接口安全域名」
微信公众平台 → 公众号设置 → 功能设置 → JS 接口安全域名。
可以填
https://xxxx.xxx.xxx,但不能带端口。你现在的地址带
:34010,微信会校验失败,所以wx.config一定会报config:invalid domain。→ 把服务反向代理到 80/443 端口,再去掉端口号再填进去。
当前页面 URL 必须与第 1 步填的域名完全一致
你在小程序里拼的
finalUrl最终是https://xxxx.xxx.xxx:34010/systemApp?code=xxx微信 SDK 在校验时会把
:34010也算进域名,于是匹配不上安全域名,同样会失败。→ 把页面地址改成
https://xxxx.xxx.xxx/systemApp?code=xxx即可。签名必须按「当前页面完整 URL」计算
后端生成 signature 时要用 浏览器地址栏里的完整 URL(含 query 部分),而不是只到 origin。
你现在传给后端的是
window.location.origin,把?code=xxx丢了,也会导致config:invalid signature。→ 改成
只要以上三点全部对齐,
wx.config就能成功。总结:把端口去掉、域名保持一致、签名用完整 URL,即可正常初始化 weixin-js-sdk。
要回复问题请先登录或注册
公告
更多>相关问题