You need to enable JavaScript to run this app.
导航
SDK 参考 Demo
最近更新时间:2025.01.07 14:26:09首次发布时间:2024.12.20 16:16:51

免责说明

说明

本demo仅供参考与学习之用,不构成任何形式的商业建议或法律建议。我们尽力确保内容的准确性和完整性,但不保证代码的时效性、可靠性或适用性。你可以根据项目的具体情况添加更多细节,比如数据隐私、软件授权或具体责任限制。如果你还需要针对某个场景定制化,请告诉我们。

安全建议

说明

  1. 火山AK、SK属于敏感信息,请不要将其上传至代码托管平台(如Github)或者未加密存储。
  2. 不要将火山AK、SK放在H5页面内,火山AK、SK应该妥善保管在用户的后端服务器内用于签名。

Demo

前置依赖引入

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- 用户代码 -->
    <!-- 引入依赖 -->
    <script src="https://cloud-security.volccdn.com/obj/cloud-security/volc-number-auth-web-sdk-v1.0.js"></script>
  </head>
  <body>
    <!-- 用户代码 -->
  </body>
</html>

页面交互逻辑 Demo

Demo1:内嵌掩码

核心部分代码

function App() {
  // 判断是否展示本身的取号模块
  const [userAuthVisible, setUserAuthVisible] = useState<boolean>(true);
  // 授权弹窗的样式配置
  const [authStyleConfig, setAuthStyleConfig] = useState<StylesConfigType>({});
  const [phone, setPhone] = useState('');

  // 取号成功回调
  const onSuccess: SuccessCallbackType = async response => {
    if (response?.code === '103000') {
      if (response?.message === '弹窗加载成功') {
        // 弹窗加载成功
        setUserAuthVisible(false);
      } else if (response?.token) {
        const chinaMobile = spSign?.ChinaMobile ?? {};
        // 请求后端,换取真实的手机号
        const phone = await api.tokenValidateChinaMobile({
          SPTToken: response?.token,
          UserInformation: response?.userInformation,
          APPID: chinaMobile?.APPID,
          VolcSign: chinaMobile?.SPSign,
          TraceID: chinaMobile?.TraceID,
          TimeStamp: chinaMobile?.TimeStamp,
        });
        setUserAuthVisible(true);
        setPhone(phone);
      }
    }
  };
  // 取号失败回调
  const onError: ErrorCallbackType = err => {
    if (err?.message === '用户点击控件') {
      // 更换号码,退出取号
      setUserAuthVisible(true);
    }
  };
  
  const fetchSpSign = async () => {
    const spSign = await api.getSpSign({
        // 该参数获取途径:火山引擎-资质管理-安全认证页面-APPID
        VolcAPPID: 'xxx'
    });
    setSpSign(spSign)
    return spSign
  }


  const getToken = async () => {
    const getTokenInfo = window.volcNumberAuthWebSdk.getTokenInfo;
    // 通过后端接口获取签名参数
    const spSign = await fetchSpSign()
    const { styleConfig } = getTokenInfo({
      spSign,
      data: {
        version: VERSION,
        authPageType: '2',
      },
      // 使用默认样式
      isUseDefaultStyle: true,
      styles: {
        agreeStyle: {
          agreeArr: [{ name: '《用户使用协议xxxx》', url: 'https://www.xxxx.com/' }], // 请按需修改
        },
      },
      onSuccess,
      onError,
    });
    setAuthStyleConfig(styleConfig);
  };
  useEffect(() => {
    // 开始取号
    getToken();
  }, []);
  return (
    <div className="container">
       <div
        style={{
          backgroundColor: '#f24f44',
        }}
      >
        <div id="ydrzCustomControls" />
        {userAuthVisible && (
          <PhoneAuth authStyleConfig={authStyleConfig} phone={phone} />
        )}
      </div>
    </div>
  );
}

详细代码

https://codesandbox.io/p/sandbox/pc9x4f

Demo 2:弹窗式

核心部分代码

import { useCallback, useEffect, useState } from 'react';
import { Popup } from '@arco-design/mobile-react';
import PhoneAuth from './components/phone-auth';
import { APP_ID, SIGN, VERSION, TRACE_ID, TIMESTAMP } from './constant';
import {
  ErrorCallbackType,
  StylesConfigType,
  SuccessCallbackType,
} from './types';
import * as api from './api';
import './style/reset.css';
import './index.css';

function App() {
  const [popupVisible, setPopupVisible] = useState<boolean>(false);
  const [authStyleConfig, setAuthStyleConfig] = useState<StylesConfigType>({});
  const [phone, setPhone] = useState('');
  
  const [spSign, setSpSign] = useState();

  // 取号成功回调
  const onSuccess: SuccessCallbackType = async response => {
    if (response?.code === '103000') {
      if (response?.message === '弹窗加载成功') {
        // 弹窗加载成功
        setPopupVisible(true);
      } else if (response?.token) {
        // 请求后端,换取真实的手机号
        const chinaMobile = spSign?.ChinaMobile ?? {};
     
        const phone = await api.tokenValidateChinaMobile({
          SPTToken: response?.token,
          UserInformation: response?.userInformation,
          APPID: chinaMobile?.APPID,
          VolcSign: chinaMobile?.SPSign,
          TraceID: chinaMobile?.TraceID,
          TimeStamp: chinaMobile?.TimeStamp,
        });
        setUserAuthVisible(false);
        setPhone(phone);
      }
    }
  };
  // 取号失败回调
  const onError: ErrorCallbackType = err => {
    if (err?.message === '用户点击控件') {
      // 更换号码,退出取号
      setPopupVisible(false);
    }
  };
  
  const fetchSpSign = async () => {
    const spSign = await api.getSpSign({
        // 该参数获取途径:火山引擎-资质管理-安全认证页面-APPID
        VolcAPPID: 'xxx'
    });
    setSpSign(spSign)
    return spSign
  }

  const getToken = async () => {
    const getTokenInfo = window.volcNumberAuthWebSdk.getTokenInfo;
    // 通过后端接口获取签名参数
    const spSign = await fetchSpSign()
    const { styleConfig } = getTokenInfo({
      spSign,
      data: {
        version: VERSION,
        authPageType: '2',
      },
      // 使用默认样式
      isUseDefaultStyle: true,
      styles: {
        layerStyle: {
          height: '260px',
        },
        submitBtnStyle: {
          high: '150px',
        },
        agreeStyle: {
          agreeArr: [{ name: '《用户使用协议》', url: 'baidu.com' }],
        },
      },
      onSuccess,
      onError,
    });
    setAuthStyleConfig(styleConfig);
  };

  useEffect(() => {
    getToken();
  }, []);
  return (
    <div className="container">
      <div
        style={{
          backgroundColor: '#f24f44',
        }}
      >
        <PhoneAuth authStyleConfig={authStyleConfig} phone={phone} />
      </div>
      <Popup
        visible={popupVisible}
        close={() => setPopupVisible(false)}
        // 进页面的时候就渲染
        mountOnEnter={false}
        // 弹窗隐藏时不销毁
        unmountOnExit={false}
        contentStyle={{ borderRadius: '10px 10px 0 0', overflow: 'hidden' }}
      >
        <div
          style={{
            backgroundColor: '#f24f44',
            paddingTop: '40px',
          }}
        >
          <div id="ydrzCustomControls" />
        </div>
      </Popup>
    </div>
  );
}

export default App;