ReOTP.
开发者工具包/ReOTP Node.js Library
1 阅读需1分钟

ReOTP Node.js Library

一个开箱即用的库,旨在简化在 Node.js/Next.js 应用中使用 ReOTP。

无需手动编写 HTTP 请求,您可以使用我们简单的 SDK 代码在几秒钟内集成 ReOTP。

该库是一个开箱即用的包装器(Wrapper),您可以直接将其作为 reotp.tsreotp.js 文件复制到您的项目中并使用。

特性

  • 自动发送 Init 并处理错误。
  • 提供内置的 SSE (Server-Sent Events)(持续状态检查)函数。
  • 提供强大的 TypeScript 类型支持。
集成代码(SDKs)
export class ReOTPClient {
  private apiKey: string;
  private baseUrl: string;

  constructor(apiKey: string, baseUrl: string = "https://your-domain.com") {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
  }

  async verify(phoneNumber: string, method: "WHATSAPP" | "TELEGRAM" = "WHATSAPP") {
    const res = await fetch(`${this.baseUrl}/api/verify/init`, {
      method: "POST",
      headers: { 
        "Content-Type": "application/json",
        "Authorization": `Bearer ${this.apiKey}`
      },
      body: JSON.stringify({ phoneNumber, method })
    });
    
    if (!res.ok) throw new Error(await res.text());
    return await res.json(); // { requestId, waLink, tgLink, expectedText }
  }

  async waitForVerification(requestId: string, timeoutMs: number = 120000): Promise<boolean> {
    return new Promise((resolve, reject) => {
      const EventSource = require('eventsource');
      const evtSource = new EventSource(`${this.baseUrl}/api/verify/stream?id=${requestId}`);

      const timeout = setTimeout(() => {
        evtSource.close();
        resolve(false);
      }, timeoutMs);

      evtSource.onmessage = (event: any) => {
        const data = JSON.parse(event.data);
        if (data.status === "VERIFIED") {
          clearTimeout(timeout);
          evtSource.close();
          resolve(true);
        } else if (data.status === "EXPIRED") {
          clearTimeout(timeout);
          evtSource.close();
          reject(new Error("Session expired"));
        } else if (data.status === "REJECTED") {
          clearTimeout(timeout);
          evtSource.close();
          reject(new Error(data.failureReason || "Session rejected"));
        }
      };

      evtSource.onerror = () => {
        // Fallback or retry logic can be added here
      };
    });
  }
}