昨天因为有一个项目上面需要实现h5微信授权工作。所以花了两个小时来完成这个功能。
开始工作前做的准备
流程说明【提前沟通过的流程】
域名,端口
域名和端口号的要求是因为微信公众号配置域名以及微信服务器回调都需要域名和80端口。
这里同一个域名,端口适配前后端IP,通过nginx统一代理处理。
准备就绪开始工作
配置微信公众号
域名配置
服务器根路径上传校验文件,不然域名配置保存不了。
白名单配置
书写代码
import React, { useEffect } from "react"; import { View } from "@tarojs/components"; export default () => { useEffect(() => { // 后端回调回来路径格式:http://xxx.cn/#/pages/webAuthorization?bindFlag=0&openid=xxxxxxxxxxx&unionid=null&isAuth=true var isBindFlag = false, isAuth = false, opendId = '', paramsArray = []; /* * 省略代码:地址判断,参数处理 赋值给isAuth, isBindFlag, openId */ if (!isAuth) { // 未授权 window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${'xxxxxxx'}&redirect_uri=http://xxxxx/api/auth?response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`; } else if (!isBindFlag) { // 未注册 window.location.href = '#/pages/login' } else { // 登录 window.location.href = '#/pages/index' } }, []); return ( <View> </View> ); }; |