import {TabbyPurchaseType} from '../constants/payment'; import {CheckoutSession, TabbyCheckoutPayload} from '../constants/payment'; import {getVersionHeader} from './utils/headers'; export type TabbySession = { sessionId: string; paymentId: string; availableProducts: TabbyProduct[]; rejectionReason?: string; // Optional, if the session is not available }; export enum TabbyEnv { STAGING = 'dev', PRODUCTION = 'ai', } export type TabbyProduct = { type: TabbyPurchaseType; webUrl: string; }; class TabbyRN { private env: TabbyEnv = TabbyEnv.PRODUCTION; get apiHost() { return `https://api.tabby.${this.env}/api/v2/checkout`; } get widgetsUrl() { return `https://widgets.tabby.${this.env}/tabby-promo.html`; } private apiKey: string | null = null; public setApiKey(apiKey: string, env: TabbyEnv = TabbyEnv.PRODUCTION) { this.apiKey = apiKey; this.env = env; } public async createSession( payload: TabbyCheckoutPayload, ): Promise { if (!this.apiKey) { console.error('TABBY_API_KEY is not set'); console.error( "Call Tabby.setApiKey('your_public_key') before calling Tabby.createSession()", ); throw new Error('API Key is not set'); } const response = await fetch(`${this.apiHost}`, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-SDK-Version': getVersionHeader(), Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(payload), }); if (response.ok) { const checkoutSession: CheckoutSession = await response.json(); const { id, configuration: {available_products, products}, payment, } = checkoutSession; const availableProducts: TabbyProduct[] = []; if (available_products.installments) { const [installmentsPlan] = available_products.installments; if (installmentsPlan) { availableProducts.push({ type: 'installments', webUrl: installmentsPlan.web_url, }); } } const result: TabbySession = { sessionId: id, paymentId: payment.id, availableProducts, rejectionReason: products.installments?.rejection_reason, }; return result; } else { throw new Error('Error creating session'); } } } const Tabby = new TabbyRN(); export {Tabby};