# @clue_nidapp/captcha-core

> 线索通表单短信验证码逻辑层SDK，配合表单逻辑层SDK @clue_nidapp/form-core使用

Latest version **2.0.1-alpha.3** (published 2023-02-08) · MIT license · 0 weekly downloads

## Install

```sh
npm install @clue_nidapp/captcha-core
pnpm add @clue_nidapp/captcha-core
yarn add @clue_nidapp/captcha-core
bun add @clue_nidapp/captcha-core
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.0.1-alpha.3 |
| Published | 2023-02-08 |
| First published | 2022-09-26 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 3 |
| Unpacked size | 53.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | huangming.0814, liangyibo.111, swithunhan, ~month, bytednpm |

## Links

- npm: https://www.npmjs.com/package/@clue_nidapp/captcha-core
- npm.io page: https://npm.io/package/@clue_nidapp/captcha-core

## Dependencies (3)

- [deepmerge](https://npm.io/package/deepmerge.md) ^4.2.2
- [eventemitter3](https://npm.io/package/eventemitter3.md) ^4.0.4
- [@clue_nidapp/shared](https://npm.io/package/@clue_nidapp/shared.md) ^2.0.1-alpha.3

## Recent versions

- 2.0.1-alpha.3 (latest) — 2023-02-08
- 2.0.0-beta.13 (beta) — 2022-09-26
- 2.0.1-alpha.2 — 2022-11-02
- 2.0.1-alpha.1 — 2022-10-26
- 2.0.1-alpha.0 — 2022-10-17
- 2.0.0 — 2022-10-09
- 2.0.0-beta.14 — 2022-09-27

## README

# Captcha Core 相关说明

线索通表单短信验证码逻辑层SDK，配合表单逻辑层SDK @clue_nidapp/form-core使用

### 2.0升级改动

1. appId不再通过jsb去获取， 通过调用InitCodeInfo方法时传入

### 安装

```shell
yarn add @clue_nidapp/captcha-core
#or npm install @clue_nidapp/captcha-core -S

#H5环境安装api插件
yarn add @clue_nidapp/plugin-api-h5
#or npm install @clue_nidapp/plugin-api-h5 -S

#Lynx环境安装api插件
yarn add @clue_nidapp/plugin-api-lynx
#or npm install @clue_nidapp/plugin-api-lynx -S

#小程序环境安装api插件
yarn add @clue_nidapp/plugin-api-mini
#or npm install @clue_nidapp/plugin-api-mini -S
```

### H5使用（react为例）

```typescript jsx
import React, { useCallback, useEffect, useReducer, useRef } from 'react';
import {
  Core as CaptchaCore,
  SmsCodeEvent,
  CaptchaLifeCycleEvent,
  ValidateType,
  SendSmsCodeResponse,
  ChannelType,
} from '@clue_nidapp/captcha-core';

import { Api as requestPlugin } from '@clue_nidapp/plugin-api-h5';

interface CaptchaProps {
  validateType: ValidateType; // 验证码类型
  phoneNumber: string; // 电话，必传
  secretPhoneId: string; // 加密电话号码的 uuid
  validateImgUrl: string; // 图片验证码url
  intervalTime: number; //获取验证码时间间隔
  appId?: number; // 历史填充分端隔离使用，没用到历史填充可不传
}

interface CaptchaState {
  graphCaptchaTip: string;
  validateImgUrl: string;
  smsTicket: string;
  smsCountDown: number;
}

function Captcha(props: CaptchaProps) {
  let { current: captchaCore } = useRef<CaptchaCore>();
  const { validateType, phoneNumber, secretPhoneId, validateImgUrl, intervalTime } = props;
  const [captchaState, setCaptchaState] = useReducer(
    (preState: CaptchaState, newState: Partial<CaptchaState>) => {
      return { ...preState, ...newState };
    },
    {
      graphCaptchaTip: '',
      validateImgUrl: '',
      smsTicket: '',
      smsCountDown: 60,
    },
  );

  useEffect(() => {
    const captchaCore = new CaptchaCore({
      validateType,
      plugins: [new requestPlugin()],
    });
    captchaCore.InitCodeInfo({
      phoneNumber,
      secretPhoneId,
      validateImgUrl,
      intervalTime,
      channel: ChannelType.chengzijianzhan
    });
    captchaCore.on(CaptchaLifeCycleEvent.GetCodeFail, (res: SendSmsCodeResponse) => {
      setCaptchaState({
        graphCaptchaTip: res.message,
      });
    });
    captchaCore.on(CaptchaLifeCycleEvent.GetCodeSuccess, () => {
      console.log('captcha: 发送成功');
    });
    captchaCore.on(CaptchaLifeCycleEvent.SubmitSuccess, (res: any) => {
      // 验证成功,后续res.data.smsTicket会在表单再次提交时使用
      setCaptchaState({
        smsTicket: res.data.smsTicket,
      });
    });
    captchaCore.on(CaptchaLifeCycleEvent.SubmitFail, message => {
      console.warn('captcha: fail', message);
    });
    captchaCore.on(CaptchaLifeCycleEvent.SubmitError, error => {
      console.warn('captcha: error', error);
    });
    captchaCore.on(SmsCodeEvent.CountDown, count => {
      setCaptchaState({
        smsCountDown: count,
      });
    });

    return () => {
      captchaCore?.destroy();
    };
  }, []);

  const getCode = useCallback(() => {
    captchaCore?.getCode();
  }, []);

  const changeHandler = useCallback(e => {
    captchaCore?.changeCode({
      code: e.target.value.trim(),
    });
  }, []);

  const submitHandler = useCallback(() => {
    captchaCore?.submit();
  }, []);

  return (
    <div>
      <input type="text" placeholder="请输入验证码" onChange={changeHandler} />
      <div>
        {captchaState.smsCountDown > 0 ? captchaState.smsCountDown : <button onClick={getCode}>重新获取</button>}
      </div>
      <button onClick={submitHandler}>提交短信验证码</button>
    </div>
  );
}
```

### 生命周期

|          模块           |        常量名        |         常量值         |     描述      |                返回值                | 备注  |
|:---------------------:|:-----------------:|:-------------------:|:-----------:|:---------------------------------:|:---:|
| CaptchaLifeCycleEvent |  GetCodeSuccess   |  'GetCodeSuccess'   |   获取验证码成功   |                                   |     |
|                       |    GetCodeFail    |    'GetCodeFail'    |   获取验证码失败   |     res: SendSmsCodeResponse      |     |
|                       |   GetCodeError    |   'GetCodeError'    | 获取验证码请求接口报错 |               Error               |     |
|                       | FrontValidateFail | 'FrontValidateFail' |  前端校验验证码失败  |      result: ValidateResult       |     |
|                       |   SubmitSuccess   |   'SubmitSuccess'   |   验证码提交成功   | res: SubmitSmsCodeSuccessResponse |     |
|     SmsCodeEvent      |     CountDown     |     'CountDown'     | 短信验证码获取倒计时  |           count: number           |     |

### API & 属性

|      名称      | 类型  |        参数         |       说明       | 示例  |
|:------------:|:---:|:-----------------:|:--------------:|:---:|
| InitCodeInfo | API | opts: SmsCodeInfo |    初始化验证码信息    |     |
|  changeCode  | API | { code: string }  |     输入验证码      |     |     
|   getCode    | API |         -         |     获取验证码      |     |
|    submit    | API |         -         |    提交短信验证码     |     |
|   destroy    | API |         -         | UI组件销毁时调用清除定时器 |     |

### 获取验证码失败返回值说明

```typescript
// 短信接口返回值
enum SMS_STATUS {
  SMS_VALIDATE_SUCCESS = 1,
  SMS_TIME_OVER = 4,
  NEED_PIC_VALIDATE = 5,
  SMS_SEND_SUCCESS = 6,
  PIC_VALIDATE_FAIL = 7,
  SMS_VALIDATE_FAIL = 8,
  SMS_DAY_BEYOND = 9,
  SMS_TIME_BEYOND = 10,
}

export interface SendSmsCodeResponse {
  message: string;
  pic_url: string;
  status: SMS_STATUS;
}
```

### 验证码校验失败返回值说明

```typescript
export interface ValidateResult {
  state: SMS_STATUS;
  reason: string; // message
}
```

### 验证码提交成功返回值说明

```typescript
export interface SubmitSmsCodeSuccessResponse {
  sms_ticket: string;
}
```
### 初始化验证码信息方法参数说明

```typescript
// 短信验证码初始化数据
export interface SmsCodeInfo {
  phoneNumber: string; // 电话，必传
  secretPhoneId: string; // 加密电话号码的 uuid
  validateImgUrl: string; // 图片验证码url
  intervalTime: number; //获取验证码时间间隔
  appId?: number; // 历史填充分端隔离使用
}
```

---
_Source: https://npm.io/package/@clue_nidapp/captcha-core · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
