# Berify.me React Native SDK

[![npm version](https://img.shields.io/npm/v/@bytexbyte/berifyme-react-native-sdk.svg)](https://www.npmjs.com/package/@bytexbyte/berifyme-react-native-sdk)

Berify.me React Native SDK 是一個用於 React Native 應用程式的身份驗證 (KYC/IDV) 解決方案。此 SDK 提供了一個簡單易用的 Modal 元件，讓開發者能夠快速整合多種身份驗證服務提供商。

## 📋 目錄

- [功能特色](#功能特色)
- [支援的驗證服務](#支援的驗證服務)
- [系統需求](#系統需求)
- [安裝](#安裝)
- [快速開始](#快速開始)
- [API 參考](#api-參考)
- [專案結構](#專案結構)
- [環境配置](#環境配置)
- [開發指南](#開發指南)

## ✨ 功能特色

- 🔐 **多種驗證方式**：支援多種第三方身份驗證服務商
- 📱 **手機號碼驗證**：透過 SMS 驗證碼進行使用者認證
- 🎨 **高度可自訂化**：支援自訂 Modal 外觀與行為
- 🌍 **多環境支援**：提供 Sandbox、Staging 與 Production 環境
- 🔄 **雙模式驗證**：支援 Onboarding（註冊）與 Login（登入）兩種驗證流程
- 🔒 **生物識別**：支援生物辨識（指紋、Face ID）登入

## 🔗 支援的驗證服務

| 服務商 | Onboarding | Login |
|--------|------------|-------|
| AuthID | ✅ | ✅ |
| Clear  | ✅ | ✅ |
| Incode | ✅ | ✅ |
| Sumsub | ✅ | ✅ |
| Veriff | ✅ | ✅ |
| Yoti   | ✅ | ✅ |

## 📦 系統需求

- **Node.js**: >= 18
- **React**: >= 18.0.0
- **React Native**: >= 0.71.0

### Peer Dependencies

```json
{
  "@react-native-async-storage/async-storage": ">=2.0.0",
  "react-native-biometrics": ">=3.0.1",
  "react-native-device-info": ">=13.1.0",
  "react-native-webview": ">=13.12.2"
}
```

## 📥 安裝

使用 npm：
```bash
npm install @bytexbyte/berifyme-react-native-sdk
```

使用 yarn：
```bash
yarn add @bytexbyte/berifyme-react-native-sdk
```

### 安裝 Peer Dependencies

```bash
npm install @react-native-async-storage/async-storage react-native-biometrics react-native-device-info react-native-webview
```

### iOS 配置

進入 ios 目錄並執行：
```bash
cd ios && pod install
```

## 🚀 快速開始

```tsx
import React, { useState } from 'react';
import { View } from 'react-native';
import { Berifyme } from '@bytexbyte/berifyme-react-native-sdk';

const App = () => {
  const [verificationToken, setVerificationToken] = useState<string | null>(null);

  const handleUpdate = ({ detail }) => {
    console.log('驗證狀態更新:', detail);
    
    if (detail.page) {
      console.log('當前頁面:', detail.page.pageName);
    }
    
    if (detail.message) {
      console.log('訊息:', detail.message);
    }
  };

  return (
    <View style={{ flex: 1 }}>
      <Berifyme.modal
        apiKeyId="YOUR_API_KEY_ID"
        secretKey="YOUR_SECRET_KEY"
        environment={Berifyme.environment.Sandbox}
        setGeneralVerificationToken={setVerificationToken}
        onUpdate={handleUpdate}
        // 可選：預設驗證的手機號碼
        // verifiedExternalPhoneNumber="+886912345678"
      />
    </View>
  );
};

export default App;
```

## 📖 API 參考

### Berifyme

主要匯出的物件，包含以下屬性：

| 屬性 | 類型 | 說明 |
|------|------|------|
| `modal` | Component | 驗證 Modal 元件（KYC/IDV 全流程） |
| `snapMatch` | Component | SnapMatch (1:N 人臉辨識) 元件 |
| `environment` | Enum | 環境配置列舉 |

### Modal Props

| 屬性 | 類型 | 必填 | 說明 |
|------|------|------|------|
| `apiKeyId` | `string` | ✅ | Berify.me API Key ID |
| `secretKey` | `string` | ✅ | Berify.me Secret Key |
| `environment` | `Environment` | ✅ | 運行環境 |
| `setGeneralVerificationToken` | `React.Dispatch<SetStateAction<string \| null>>` | ✅ | 設定驗證 Token 的回調函數 |
| `verifiedExternalPhoneNumber` | `string` | ❌ | 預先驗證的外部手機號碼 |
| `onUpdate` | `function` | ❌ | 狀態更新回調函數 |

### SnapMatch Props

`Berifyme.snapMatch` 是 1:N 人臉辨識元件，將 SnapMatch 流程載入 WebView，完成後以 `onSuccess` / `onError` 回傳結果。結果頁倒數結束後會自動重置進行下一輪掃臉（無限循環），也可由使用者手動點擊按鈕繼續。

**快速使用範例：**

```tsx
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { Berifyme } from '@bytexbyte/berifyme-react-native-sdk';
import type { SnapMatchUser } from '@bytexbyte/berifyme-react-native-sdk';

function SnapMatchScreen(): React.JSX.Element {
  return (
    <View style={StyleSheet.absoluteFill}>
      <Berifyme.snapMatch
        apiKeyId="YOUR_API_KEY_ID"
        secretKey="YOUR_SECRET_KEY"
        environment={Berifyme.environment.Staging}
        onSuccess={(user: SnapMatchUser) => {
          console.log('辨識成功', user.id, user.fullName);
        }}
        onError={(message: string) => {
          console.error('辨識失敗', message);
        }}
        locale="zh-TW"
        autoRedirectSeconds={5}
      />
    </View>
  );
}
```

**Props 參考：**

| 屬性 | 類型 | 必填 | 說明 |
|------|------|------|------|
| `apiKeyId` | `string` | ✅ | Berify.me API Key ID |
| `secretKey` | `string` | ✅ | Berify.me Secret Key |
| `environment` | `Environment` | ✅ | 運行環境 |
| `onSuccess` | `(user: SnapMatchUser) => void` | ✅ | 人臉辨識成功時的回調，回傳匹配的使用者資料 |
| `onError` | `(message: string) => void` | ✅ | 驗證失敗或發生錯誤時的回調，回傳錯誤訊息 |
| `token` | `string` | ❌ | 若已取得 `session_` 前綴的 token 可直接傳入；否則 SDK 自動向後端取得 |
| `locale` | `string` | ❌ | WebView 頁面語系，如 `'en'`、`'zh-TW'`，預設 `'en'`。掃臉階段會顯示語言切換按鈕（不影響結果頁） |
| `autoRedirectSeconds` | `number` | ❌ | 結果頁自動跳回掃臉的秒數，`0` 為不自動跳轉，預設 `5` |

**SnapMatchUser（`onSuccess` 回傳型別）：**

| 欄位 | 類型 | 說明 |
|------|------|------|
| `id` | `string` | Berify.me 使用者 ID |
| `fullName` | `string \| null \| undefined` | 全名 |
| `phoneNumber` | `string \| null \| undefined` | 電話號碼 |
| `email` | `string \| null \| undefined` | 電子郵件 |
| `age` | `number \| undefined` | 年齡（驗證時可取得） |
| `birthDate` | `string \| undefined` | 出生日期（驗證時可取得） |

### Environment

可用的環境選項：

| 環境 | 值 | 說明 |
|------|-----|------|
| Sandbox | `'sandbox'` | 沙盒測試環境 |
| Staging | `'staging'` | 預發布環境 |
| Idv | `'idv'` | 正式生產環境 |

### 環境對應網域

| 環境 | 後端 API | WebView |
|------|----------|---------|
| Sandbox | `https://sandbox-backend.berify.me` | `https://sandbox.berify.me` |
| Staging | `https://staging-backend.berify.me` | `https://staging.berify.me` |
| Idv | `https://backend.berify.me` | `https://idv.berify.me` |

## 📁 專案結構

```
src/
├── index.tsx                  # SDK 入口點
├── BerifymeModal/
│   ├── index.tsx              # Modal 主核心，使用 useState 切換頁面狀態
│   └── MainModal.tsx          # Modal 外觀元件
├── components/
│   ├── SnapMatch.tsx          # SnapMatch (1:N 人臉辨識) 元件
│   ├── Onboarding/            # Onboarding 相關元件
│   ├── SendSNS/               # SMS 驗證相關元件
│   ├── VerifyWithPhoneNumber/ # 手機號碼驗證元件
│   ├── VerifiedExternalPhoneNumber/ # 外部手機號碼驗證
│   ├── biometrics/            # 生物識別相關元件
│   ├── AuthidLogin.tsx        # AuthID 登入
│   ├── AuthidOnboarding.tsx   # AuthID Onboarding
│   ├── ClearLogin.tsx         # Clear 登入
│   ├── ClearOnboarding.tsx    # Clear Onboarding
│   ├── IncodeOnBoarding.tsx   # Incode Onboarding
│   ├── incodeLogin.tsx        # Incode 登入
│   ├── SumsubLogin.tsx        # Sumsub 登入
│   ├── SumsubOnboarding.tsx   # Sumsub Onboarding
│   ├── VeriffLogin.tsx        # Veriff 登入
│   ├── VeriffOnboarding.tsx   # Veriff Onboarding
│   ├── YotiLogin.tsx          # Yoti 登入
│   ├── YotiOnboarding.tsx     # Yoti Onboarding
│   ├── AllSet.tsx             # 驗證完成頁面
│   ├── SomethingWrong.tsx     # 錯誤處理頁面
│   └── Footer.tsx             # 頁腳元件
├── api/
│   └── api.ts                 # API 請求封裝
├── enum/
│   └── index.tsx              # 列舉定義（環境、頁面狀態等）
├── environmentDomains.ts      # 環境網域配置
├── countryCode.ts             # 國碼資料
└── phoneNumberProcessor.ts    # 手機號碼處理工具
```

## 🔧 開發指南

### 本地開發

```bash
# 安裝依賴
yarn install

# 啟動 Metro bundler
yarn start

# 運行 iOS
yarn ios

# 運行 Android
yarn android
```

### 構建發布

```bash
# 準備構建
yarn prepare

# 發布到 npm
yarn release
```

### 程式碼檢查

```bash
# ESLint 檢查
yarn lint

# 測試
yarn test
```

## 📂 Git 倉庫

- **位置**: https://dev.azure.com/ByteXByte/Berify.me/_git/Berify.me-ReactNativeSDK
- **HTTPS**: https://ByteXByte@dev.azure.com/ByteXByte/Berify.me/_git/Berify.me-ReactNativeSDK
- **SSH**: git@ssh.dev.azure.com:v3/ByteXByte/Berify.me/Berify.me-ReactNativeSDK

## 📄 授權

此專案為 ByteXByte 所有。

---

© 2024 ByteXByte. All Rights Reserved.