ReOTP.
حزم المطورين/مكتبة ReOTP لـ Node.js
1 دقيقة قراءة

مكتبة ReOTP لـ Node.js

مكتبة جاهزة لتسهيل استخدام ReOTP في تطبيقات Node.js/Next.js.

بدلاً من كتابة طلبات الـ HTTP يدوياً، يمكنك استخدام كود الـ SDK البسيط الخاص بنا لدمج ReOTP في ثوانٍ.

هذه المكتبة هي Wrapper جاهز يمكنك نسخه مباشرة في مشروعك كملف reotp.ts أو reotp.js واستخدامه.

المميزات

  • إرسال الـ Init تلقائياً والتعامل مع الأخطاء.
  • توفير دالة للـ SSE (Server-Sent Events) (فحص الحالة المستمر) مدمجة.
  • توفير أنواع Typescript قوية.
كود التكامل (SDKs)
export class ReOTPClient {
  private apiKey: string;
  private baseUrl: string;

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

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

  async waitForVerification(requestId: string, timeoutMs: number = 120000): Promise<{ verified: boolean; phoneNumber?: string }> {
    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({ verified: false });
      }, timeoutMs);

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

      evtSource.onerror = () => {
        // Fallback or retry
      };
    });
  }
}