Quran_Tech_Server / F_Pro /src /lib /api /paymentApi.ts
aboalaa147's picture
Initial deployment
eb6a2f9
Raw
History Blame Contribute Delete
2.88 kB
// 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<InitiatePaymentResponse> {
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<InitiatePaymentResponse>;
}
/**
* POST /api/payments/confirm-payment/{paymentIntentId}
* ูŠุคูƒุฏ ู„ู„ู€ Backend ุฅู† Stripe ู†ุฌุญ
*/
export async function confirmPaymentWithBackend(
paymentIntentId: string
): Promise<ConfirmPaymentResponse> {
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<ConfirmPaymentResponse>;
}