72 lines
2.5 KiB
TypeScript
72 lines
2.5 KiB
TypeScript
// ─── Pricing Utilities ─────────────────────────────────────────────────────────
|
|
|
|
import { PAYME_CONFIG, PRICING } from './constant';
|
|
import {
|
|
PaymePaymentRequest,
|
|
PaymePaymentResponse,
|
|
ServicePricing,
|
|
} from './types';
|
|
|
|
export const getPricing = (): ServicePricing => ({
|
|
serviceFee: PRICING.SERVICE_FEE,
|
|
certificateFee: PRICING.CERTIFICATE_FEE,
|
|
currency: PRICING.CURRENCY,
|
|
});
|
|
|
|
export const calculateTotal = (hasCertificate: boolean): number => {
|
|
const base = PRICING.SERVICE_FEE;
|
|
return hasCertificate ? base + PRICING.CERTIFICATE_FEE : base;
|
|
};
|
|
|
|
export const toTiyin = (uzs: number): number => uzs * PRICING.TIYIN_MULTIPLIER;
|
|
|
|
export const formatPrice = (amount: number, currency: string): string =>
|
|
`${amount.toLocaleString('uz-UZ')} ${currency}`;
|
|
|
|
// ─── Order ID Generator ────────────────────────────────────────────────────────
|
|
|
|
export const generateOrderId = (): string => {
|
|
const timestamp = Date.now();
|
|
const random = Math.random().toString(36).slice(2, 8).toUpperCase();
|
|
return `ORDER-${timestamp}-${random}`;
|
|
};
|
|
|
|
// ─── Payme API ─────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Sends payment details to the backend, which creates a Payme transaction
|
|
* and returns a redirect URL to the Payme checkout page.
|
|
*/
|
|
export const createPaymePayment = async (
|
|
request: PaymePaymentRequest,
|
|
): Promise<PaymePaymentResponse> => {
|
|
const response = await fetch(PAYME_CONFIG.API_ENDPOINT, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
amount: request.amount, // in tiyin
|
|
order_id: request.orderId,
|
|
description: request.description,
|
|
return_url: request.returnUrl,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorBody = await response.json().catch(() => ({}));
|
|
throw new Error(
|
|
(errorBody as { message?: string }).message ??
|
|
`Payment request failed with status ${response.status}`,
|
|
);
|
|
}
|
|
|
|
const data = (await response.json()) as PaymePaymentResponse;
|
|
return data;
|
|
};
|
|
|
|
/**
|
|
* Redirects the user to the Payme checkout page.
|
|
*/
|
|
export const redirectToPayme = (redirectUrl: string): void => {
|
|
window.location.href = redirectUrl;
|
|
};
|