react+nodejs+腾讯云短信实现真实手机号验证码登录

react项目之真实手机号验证码登录

第一步如果你有腾讯云短信接口这一步可以直接省略,如果你没有请根据我的步骤进行申请“腾讯云短信接口”

登录或者注册腾讯云账号

react+nodejs+腾讯云短信实现真实手机号验证码登录_第1张图片

第三步去申请腾讯云提供的免费100条的短信

第四步创建一个签名

react+nodejs+腾讯云短信实现真实手机号验证码登录_第2张图片

完成上述步骤,就可以开始使用了

现在是对后端nodejs的使用
nodejs版本最好在16以上,不然会报错
在下述代码中我写入了两个接口

//手机验证码
router.get('/sms', async function(req, res, next) {
  var temp = Math.random() * 9000; //[0,9000) 
  // 获取1000~9000
  temp = 1000 + parseInt(temp);
  
  let phone = req.query.phone;
  console.log(phone)
  // Depends on tencentcloud-sdk-nodejs version 4.0.3 or higher
  const tencentcloud = require("tencentcloud-sdk-nodejs-sms");

  const SmsClient = tencentcloud.sms.v20210111.Client;

  // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
  // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
  // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
  const clientConfig = {
      credential: {
          // 密钥id
          secretId: "自己的secretId",  //用于标识 API 调用者身份,可以简单类比为用户名。
          // 密钥密码
          secretKey: "自己的密匙", //用于验证 API 调用者的身份,可以简单类比为密码。
      },
      region: "ap-beijing",
      profile: {
          httpProfile: {
              endpoint: "sms.tencentcloudapi.com",
          },
      },
  };

  // 实例化要请求产品的client对象,clientProfile是可选的
  const client = new SmsClient(clientConfig);
  const params = {
      "PhoneNumberSet": ["+86"+phone],
      "SmsSdkAppId": "自己的SmsSdkAppId",
      "SignName": "自己的公众号名称",
      "TemplateId": "自己的TemplateId",
      "TemplateParamSet": [temp.toString()]
  };
  client.SendSms(params).then(
      (data) => {
          res.send({code:200,msg:"验证码发送成功",yanZhengMa:temp.toString(),data})
      },
      (err) => {
          console.error("error", err);
      }
  );
});


router.get('/yanlogin', async function(req, res, next) {
  console.log(123)
  let data=await usersModel.find({zhanghao:'13730401127'})
  if(data.length!==0){
    res.send({
      code:200,
      msg:"用户登录成功",
      data
    })
  }else{
    res.send({
      code:201,
      msg:"用户账号或者密码错误"
    })
  }
});

我们在创建签名的时候,你需要创建一个公众号或者小程序,不然无法进行申请。

前端react操作如下

在前端react中我创建了输入手机号页面和输入验证码页面
首先是手机号页面
后续则是验证码页面

下述是手机号页面

import axios from 'axios'
import React, { useState } from 'react'
import { Button, Input, Toast, Form } from 'react-vant'
import { useHistory } from 'react-router-dom'
import './yan.less'

export default () => {
  const history = useHistory(); // 获取history对象

const onFinish = (values) => {
  console.log(values);
};

const [phone, setPhone] = useState(''); // 手机号状态
const handlePhoneChange = (e) => {
  setPhone(e.target.value); // 更新手机号状态
};

const submit = async () => {
  try {
    const response = await axios.get(`http://localhost:3100/gyq/sms/?phone=${phone}`); // 发送获取验证码的请求
    const data = response.data; // 获取响应数据
    console.log(response);
    if (data.code === 200) { // 验证码发送成功
      Toast.success('验证码发送成功'); // 显示成功提示
      history.push('/需要跳转的验证码页面', { code: data.yanZhengMa }); // 跳转到glogin页面,并传递验证码参数
    } else {
      Toast.fail('有错误'); // 请求失败,显示错误提示
    }
  } catch (error) {
    Toast.fail('网络请求失败'); // 网络请求失败,显示错误提示
    console.error(error);
  }
};

  return (
    <div className='yan_main'>
      <img src={require('../../public/images/444.png')} />
      <div className='yan_ma'>
      <Form
      onFinish={onFinish}
      footer={
        <div style={{ margin: '16px 16px 0' }}>
          <Button round nativeType='submit' type='primary' onClick={submit} block>
            发送
          </Button>
        </div>
      }
    >
      <Form.Item
        name='text1'
        label='手机号'
        rules={[{ pattern: /\d{11}/, message: '请输入11位手机号' }]}
      >
        <Input placeholder='请输入您的手机号' onBlur={handlePhoneChange} />
      </Form.Item>
    </Form>
      </div>
        
    </div>
    
  )
}

下述是验证码页面

import React, { useEffect, useState } from 'react';
import { ArrowLeft } from '@react-vant/icons';
import { useHistory, useLocation } from 'umi';
import { NumberKeyboard, PasscodeInput, Space } from 'antd-mobile';
import axios from 'axios';

const Code = (props) => {
  const [time, usetime] = useState(60); // 倒计时时间状态
  const [flag, useflag] = useState(true); // 倒计时标志状态
  const location = useLocation();  // 获取当前页面路由信息
  const { code } = location.query; // 获取路由参数中的code
  const history = useHistory(); // useHistory用于进行路由跳转

  useEffect(() => {
    let timer = 60; // 初始倒计时时间为60秒
  
    // 创建定时器,每隔1秒更新倒计时时间
    const interval = setInterval(() => {
      timer--;
      usetime(timer); // 更新倒计时时间状态
  
      if (timer <= 0) {
        clearInterval(interval); // 当倒计时时间归零时,清除定时器
        useflag(false); // 更新倒计时标志状态为false,表示倒计时结束
      }
    }, 1000);
  
    // 组件卸载时清除定时器
    return () => {
      clearInterval(interval);
    };
  }, []);
  

  const fanhui = () => {
    history.goBack(); // 返回上一页
  };

  const sub = (e) => {
    axios.get("http://localhost:3100/gyq/yanlogin").then((val) => {
      console.log(val); // 打印返回的响应数据
      sessionStorage.setItem("token", JSON.stringify(val.data.data[0])); // 将响应数据中的第一个数据项存储到sessionStorage中
      alert('验证码输入成功'); // 弹出提示框,表示验证码输入成功
      history.push('/index/home'); // 跳转到首页
    });
  };
  

  return (
    <div id="code">
      <div className='top'>
        <div>
          <ArrowLeft style={{ marginTop: "30px" }} fontSize="20px" onClick={() => fanhui()} />
        </div>
        <p>
          验  证  码  登  录
        </p>
      </div>
      <div className='con'>
        <div className='title'>请输入验证码</div>
        <div className='info'>验证码已发送至 +86 {props.phone ? props.phone.slice(0, 3) + '****' + props.phone.slice(8) : ''}</div>
        <div className='box'>
          <PasscodeInput length={4} plain keyboard={<NumberKeyboard />} onFill={(e) => sub(e)} />
        </div>
        <div className='daojishi'>{flag ? `${time}s后重新获取验证码` : ''}</div>
      </div>
    </div>
  );
};

export default Code;

到这里也就结束了,记得点赞哦
react+nodejs+腾讯云短信实现真实手机号验证码登录_第3张图片

你可能感兴趣的:(react.js,腾讯云,前端,node.js)