微信公众号授权

328 阅读1分钟

设置网页授权域名

开发者需要先到公众平台官网中的设置与开发-功能设置-网页授权域名完成配置

graph TD
A[用户] --> B[authorize页面]
B --未绑定--> C[绑定页面]
C --> D
B --已绑定--> D[主流程页面]

authorize页面

import {useRouter} from "@tarojs/taro";
import {AuthCode, AfreshAuth} from './components';

const Authorize = () => {
  const {params} = useRouter();
  // 微信授权code
  if (params.code) return <AuthCode />
  return (
    <AfreshAuth />
  );
};

export default Authorize;

AuthCode组件

import Api from '@/servers/api';
import Taro, {useRouter} from '@tarojs/taro';
import {useRequest} from 'ahooks';
import {ErrorBlock} from 'antd-mobile';
import Loading from './Loading';

const AuthCode = () => {
    const {params} = useRouter();
    const {error} = useRequest(Api.shouquandenglu.postOauthLoginWechatCode,
        {
            defaultParams: [{code: params.code}],
            onSuccess: async (data) => {
                if (data.bind) {
                    Taro.setStorageSync('bind_token', data.bind_token)
                    // 未绑定,跳转绑定页面
                    Taro.reLaunch({
                        url: '/pages/binding/index',
                    });
                    return
                }
                // 已绑定,跳转到主流程页面
                Taro.setStorageSync('token', data.token)
                Taro.reLaunch({
                    url: '/pages/home/index',
                });
            },
        },
    );
    if (error) {
        return <ErrorBlock fullPage />;
    }
    return <Loading />;
};

export default AuthCode;

AfreshAuth组件

import Loading from '@/pages/authorize/components/Loading';
import Api from '@/servers/api';
import Taro from '@tarojs/taro';
import { useRequest } from 'ahooks';

const AfreshAuth = () => {
  // 判断是否登录
  useRequest(Api.shouquandenglu.getOauthCheckLogin, {
    onSuccess: () => {
      // 已登录,跳转到主流程页面
      Taro.reLaunch({
        url: '/pages/home/index',
      });
    },
    onError: async () => {
      // 未登录,跳转到授权页面
      const { redirect_url } = await Api.shouquandenglu.getOauthWechat({
        redirectUrl: window.origin,
      });
      window.location.href = redirect_url!;
    },
  });

  return <Loading />;
};

export default AfreshAuth;