React+TS+hooks使用JSSDK,公众号分享页面以及未
2021-07-24 本文已影响0人
Poppy11
此处封装了一个公共方法,因为官方介绍说,如果是SPA应用的话,每个页面都需要注入微信的配置。该配置是需要Service返回JSSDK签名。我用的是NestJS写的后端,算法详情可以看下面这个文章。
NestJS(NodeJS)使用JS-SDK签名算法
在src/react-app-env.d.ts文件下添加配置
declare var wx:any;
获取Service返回的配置后,React在需要使用分享接口的页面,注入配置。wxShareConfig 是我封装的公共方法。
export const wxShareConfig = async (title: string, des: string, url: string) => {
// 获取微信初始化配置
let locationUrl = window.location.href.split('#')[0];
let resp = await getWXConfig(locationUrl);
wx.config({
debug: false,
appId: resp.data.appId,
timestamp: resp.data.timestamp,
nonceStr: resp.data.nonceStr,
signature: resp.data.signature,
jsApiList: resp.data.jsApiList,
});
wx.ready(() => {
wx.updateAppMessageShareData({
title: title, // 分享标题
desc: des, // 分享描述
link: url,
imgUrl: 'https://joinus.newegg.cn/static/newegg.png', // 分享图标
});
});
wx.error((res: any) => { });
}
例如在A页面使用
useEffect(() => {
wxShareConfig('应聘实习生 - 提交资料', '应聘实习生 - 提交资料', 'https://joinus.newegg.cn/#/bridge?router=form');
}, []);
因为微信公众号,需要绑定个调用JSSDK接口的域名。但是现在就有个问题,微信官方跳转链接必须是在配置的JSSDK接口域名下的页面。所以我们就没办法使用微信提供的跳转链接。当用户分享该页面给好友时。就没办法回调到我们的业务页面,也就没办法获取Code,通过Code去换取OpenID。若不太明白这个Code换取OpenID的流程。可以看看下面这篇微信官方文章。
也就是好友打开的页面应该是下面这个拼接后的链接
通过第三者去转发到我们的页面
在上面wxShareConfig 这个公共方法里面大家也看到了,我接受的Link其实是我域名下的一个页面,只是带了Query。我通过不同的Query中的参数router。来区分当前页面应该跳转到微信提供的哪个拼接后的链接。也就是好友打开我分享出来的页面,先是跳转到bridge页面,bridge页面在通过不同的参数,跳转到不同的链接。
若是不知道分割Query的方法,可查看以下链接,Hash路由或者普通路由都提供了不同方法
Hash和非Hash路由获取Query值的方法
import React, { useEffect } from 'react';
import { filterUrlHashParams } from '../../common/filterUrlParams';
export default function Bridge() {
useEffect(() => {
const router = filterUrlHashParams();
if (router == 'form') {
window.location.replace(buildWXUrl('https%3A%2F%2Fjoinus.newegg.cn%2F%23%2Fform'));
} else if (router == 'vita') {
window.location.replace(buildWXUrl('https%3A%2F%2Fjoinus.newegg.cn%2F%23%2Fform'));
} else if (router == 'progress') {
window.location.replace(buildWXUrl('https%3A%2F%2Fjoinus.newegg.cn%2F%23%2Fstep'));
}
}, []);
const buildWXUrl = (url: string) => {
return ` 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=【APPID】&redirect_uri=${url}&response_type=code&scope=snsapi_base#wechat_redirect'`;
};
return <div />;
}