# مكتبة ReOTP لـ Node.js مكتبة جاهزة لتسهيل استخدام ReOTP في تطبيقات Node.js/Next.js. --- بدلاً من كتابة طلبات الـ HTTP يدوياً، يمكنك استخدام كود الـ SDK البسيط الخاص بنا لدمج ReOTP في ثوانٍ. هذه المكتبة هي Wrapper جاهز يمكنك نسخه مباشرة في مشروعك كملف `reotp.ts` أو `reotp.js` واستخدامه. ### المميزات - إرسال الـ Init تلقائياً والتعامل مع الأخطاء. - توفير دالة للـ SSE (Server-Sent Events) (فحص الحالة المستمر) مدمجة. - توفير أنواع Typescript قوية. ## Code Examples ### reotp.ts (SDK) ```typescript 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 { 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 }; }); } } ``` ### Usage Example ```typescript import { ReOTPClient } from "./reotp"; const reotp = new ReOTPClient("YOUR_API_KEY", "https://your-domain.com"); async function startLoginFlow(phoneNumber: string) { try { // 1. Init verification const session = await reotp.verify(phoneNumber, "WHATSAPP"); console.log("Session ID:", session.requestId); // -> Here: Redirect user to session.waLink // 2. Wait for verification (listens automatically via SSE) const isVerified = await reotp.waitForVerification(session.requestId); if (isVerified) { console.log("Success! Log the user in."); } else { console.log("Verification expired or failed."); } } catch (error) { console.error("Error:", error.message); } } ```