// src/lib/api/paymentApi.ts // Stripe Payment API — يُستخدم بعد قبول الشيخ للجلسة import { getApiBaseUrl } from './config'; const BASE_URL = getApiBaseUrl(); const TOKEN_KEY = 'authToken'; // ─── Types ──────────────────────────────────────────────────── export interface InitiatePaymentRequest { sessionId: number; studentId: number; sheikhId: number; amount: number; } export interface InitiatePaymentResponse { publishableKey: string; clientSecret: string; paymentIntentId: string; } export interface ConfirmPaymentResponse { success: boolean; message: string; sessionId?: number; paymentIntentId?: string; } // ─── Error Class ────────────────────────────────────────────── export class PaymentApiError extends Error { public readonly status: number; constructor(status: number, message: string) { super(message); this.status = status; this.name = 'PaymentApiError'; } } // ─── Helper ─────────────────────────────────────────────────── function getAuthHeaders(): HeadersInit { const token = localStorage.getItem(TOKEN_KEY) ?? ''; return { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), }; } // ─── API Functions ──────────────────────────────────────────── /** * POST /api/payments/initiate/card * يبدأ عملية الدفع ويرجع clientSecret و publishableKey من Stripe */ export async function initiateCardPayment( req: InitiatePaymentRequest ): Promise { const res = await fetch(`${BASE_URL}/api/payments/initiate/card`, { method: 'POST', headers: getAuthHeaders(), body: JSON.stringify(req), }); if (!res.ok) { const msg = await res.text().catch(() => res.statusText); throw new PaymentApiError(res.status, msg); } return res.json() as Promise; } /** * POST /api/payments/confirm-payment/{paymentIntentId} * يؤكد للـ Backend إن Stripe نجح */ export async function confirmPaymentWithBackend( paymentIntentId: string ): Promise { const res = await fetch( `${BASE_URL}/api/payments/confirm-payment/${paymentIntentId}`, { method: 'POST', headers: getAuthHeaders(), } ); if (!res.ok) { const msg = await res.text().catch(() => res.statusText); throw new PaymentApiError(res.status, msg); } return res.json() as Promise; }