unified-video-framework 1.4.21 → 1.4.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ /**
2
+ * Payment Gateway Adapter Interface for Unified Video Framework
3
+ * Provides a standardized way to integrate custom payment gateways
4
+ */
5
+
6
+ export interface PaymentRequest {
7
+ userId: string;
8
+ videoId: string | number;
9
+ amount: number;
10
+ currency: string;
11
+ successUrl?: string;
12
+ cancelUrl?: string;
13
+ metadata?: Record<string, any>;
14
+ customData?: Record<string, any>;
15
+ }
16
+
17
+ export interface PaymentResponse {
18
+ success: boolean;
19
+ paymentUrl?: string;
20
+ paymentData?: any;
21
+ orderId?: string;
22
+ sessionId?: string;
23
+ error?: string;
24
+ message?: string;
25
+ }
26
+
27
+ export interface VerificationRequest {
28
+ orderId?: string;
29
+ sessionId?: string;
30
+ userId: string;
31
+ videoId: string | number;
32
+ customData?: Record<string, any>;
33
+ }
34
+
35
+ export interface VerificationResponse {
36
+ success: boolean;
37
+ verified: boolean;
38
+ accessGranted: boolean;
39
+ error?: string;
40
+ message?: string;
41
+ data?: any;
42
+ }
43
+
44
+ export interface PaymentGatewayConfig {
45
+ name: string;
46
+ displayName: string;
47
+ apiBase: string;
48
+ endpoints: {
49
+ createPayment: string;
50
+ verifyPayment?: string;
51
+ };
52
+ headers?: Record<string, string>;
53
+ customHandler?: (request: PaymentRequest, config: PaymentGatewayConfig) => Promise<PaymentResponse>;
54
+ verifyHandler?: (request: VerificationRequest, config: PaymentGatewayConfig) => Promise<VerificationResponse>;
55
+ }
56
+
57
+ export abstract class PaymentGatewayAdapter {
58
+ protected config: PaymentGatewayConfig;
59
+
60
+ constructor(config: PaymentGatewayConfig) {
61
+ this.config = config;
62
+ }
63
+
64
+ /**
65
+ * Create payment session/order
66
+ */
67
+ abstract createPayment(request: PaymentRequest): Promise<PaymentResponse>;
68
+
69
+ /**
70
+ * Verify payment completion
71
+ */
72
+ abstract verifyPayment(request: VerificationRequest): Promise<VerificationResponse>;
73
+
74
+ /**
75
+ * Get gateway display name
76
+ */
77
+ getDisplayName(): string {
78
+ return this.config.displayName || this.config.name;
79
+ }
80
+
81
+ /**
82
+ * Get gateway identifier
83
+ */
84
+ getName(): string {
85
+ return this.config.name;
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Generic Payment Gateway Adapter using fetch API
91
+ */
92
+ export class GenericPaymentGateway extends PaymentGatewayAdapter {
93
+ async createPayment(request: PaymentRequest): Promise<PaymentResponse> {
94
+ try {
95
+ // Use custom handler if provided
96
+ if (this.config.customHandler) {
97
+ return await this.config.customHandler(request, this.config);
98
+ }
99
+
100
+ // Default fetch implementation
101
+ const response = await fetch(`${this.config.apiBase}${this.config.endpoints.createPayment}`, {
102
+ method: 'POST',
103
+ headers: {
104
+ 'Content-Type': 'application/json',
105
+ ...this.config.headers
106
+ },
107
+ body: JSON.stringify(request)
108
+ });
109
+
110
+ const data = await response.json();
111
+
112
+ if (!response.ok) {
113
+ return {
114
+ success: false,
115
+ error: data.message || `HTTP ${response.status}`,
116
+ message: data.message || 'Payment creation failed'
117
+ };
118
+ }
119
+
120
+ return {
121
+ success: true,
122
+ paymentUrl: data.paymentUrl || data.Payment_Link_URL,
123
+ paymentData: data,
124
+ orderId: data.orderId || data.order_id,
125
+ sessionId: data.sessionId || data.session_id
126
+ };
127
+
128
+ } catch (error) {
129
+ console.error(`[${this.config.name}] Payment creation error:`, error);
130
+ return {
131
+ success: false,
132
+ error: error instanceof Error ? error.message : 'Unknown error',
133
+ message: 'Network error occurred'
134
+ };
135
+ }
136
+ }
137
+
138
+ async verifyPayment(request: VerificationRequest): Promise<VerificationResponse> {
139
+ try {
140
+ // Use custom verify handler if provided
141
+ if (this.config.verifyHandler) {
142
+ return await this.config.verifyHandler(request, this.config);
143
+ }
144
+
145
+ // Skip verification if no endpoint provided
146
+ if (!this.config.endpoints.verifyPayment) {
147
+ return {
148
+ success: true,
149
+ verified: true,
150
+ accessGranted: true,
151
+ message: 'Verification skipped - assuming success'
152
+ };
153
+ }
154
+
155
+ const response = await fetch(`${this.config.apiBase}${this.config.endpoints.verifyPayment}`, {
156
+ method: 'POST',
157
+ headers: {
158
+ 'Content-Type': 'application/json',
159
+ ...this.config.headers
160
+ },
161
+ body: JSON.stringify(request)
162
+ });
163
+
164
+ const data = await response.json();
165
+
166
+ if (!response.ok) {
167
+ return {
168
+ success: false,
169
+ verified: false,
170
+ accessGranted: false,
171
+ error: data.message || `HTTP ${response.status}`,
172
+ message: data.message || 'Payment verification failed'
173
+ };
174
+ }
175
+
176
+ return {
177
+ success: true,
178
+ verified: data.verified !== false,
179
+ accessGranted: data.accessGranted !== false,
180
+ data: data
181
+ };
182
+
183
+ } catch (error) {
184
+ console.error(`[${this.config.name}] Payment verification error:`, error);
185
+ return {
186
+ success: false,
187
+ verified: false,
188
+ accessGranted: false,
189
+ error: error instanceof Error ? error.message : 'Unknown error',
190
+ message: 'Network error during verification'
191
+ };
192
+ }
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Cashfree Payment Gateway Adapter
198
+ * Customized for your specific Cashfree API
199
+ */
200
+ export class CashfreePaymentGateway extends PaymentGatewayAdapter {
201
+ async createPayment(request: PaymentRequest): Promise<PaymentResponse> {
202
+ try {
203
+ console.log('[Cashfree] Creating payment with request:', request);
204
+
205
+ // Get session token for authentication
206
+ const sessionToken = sessionStorage.getItem('uvf_session_token');
207
+
208
+ if (!sessionToken) {
209
+ throw new Error('User session token not found');
210
+ }
211
+
212
+ const cashfreeRequest = {
213
+ unit_amount: request.amount,
214
+ source_type_id: 1, // Video content type
215
+ source_id: request.videoId, // This will be the video slug
216
+ success_url: request.successUrl || `${window.location.origin}${window.location.pathname}?payment=success`,
217
+ failure_url: request.cancelUrl || `${window.location.origin}${window.location.pathname}?payment=failed`,
218
+ Login_device_type: 'Web',
219
+ ...request.customData
220
+ };
221
+
222
+ console.log('[Cashfree] Sending request to:', `${this.config.apiBase}${this.config.endpoints.createPayment}`);
223
+ console.log('[Cashfree] Request payload:', cashfreeRequest);
224
+
225
+ const response = await fetch(`${this.config.apiBase}${this.config.endpoints.createPayment}`, {
226
+ method: 'POST',
227
+ headers: {
228
+ 'Content-Type': 'application/json',
229
+ 'Authorization': `Bearer ${sessionToken}`,
230
+ ...this.config.headers
231
+ },
232
+ body: JSON.stringify(cashfreeRequest)
233
+ });
234
+
235
+ const data = await response.json();
236
+ console.log('[Cashfree] API Response:', data);
237
+
238
+ if (!response.ok || !data.status) {
239
+ return {
240
+ success: false,
241
+ error: data.message || `HTTP ${response.status}`,
242
+ message: data.message || 'Cashfree payment creation failed'
243
+ };
244
+ }
245
+
246
+ return {
247
+ success: true,
248
+ paymentUrl: data.Payment_Link_URL,
249
+ paymentData: data,
250
+ orderId: data.order_id || data.orderId
251
+ };
252
+
253
+ } catch (error) {
254
+ console.error('[Cashfree] Payment creation error:', error);
255
+ return {
256
+ success: false,
257
+ error: error instanceof Error ? error.message : 'Unknown error',
258
+ message: 'Network error occurred'
259
+ };
260
+ }
261
+ }
262
+
263
+ async verifyPayment(request: VerificationRequest): Promise<VerificationResponse> {
264
+ // For Cashfree, verification might be handled by webhooks or return URL
265
+ // Since your implementation uses return URLs, we'll assume success if we reach this point
266
+ console.log('[Cashfree] Payment verification requested:', request);
267
+
268
+ return {
269
+ success: true,
270
+ verified: true,
271
+ accessGranted: true,
272
+ message: 'Cashfree payment completed via return URL'
273
+ };
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Payment Gateway Manager
279
+ * Manages multiple payment gateway adapters
280
+ */
281
+ export class PaymentGatewayManager {
282
+ private gateways: Map<string, PaymentGatewayAdapter> = new Map();
283
+
284
+ /**
285
+ * Register a payment gateway adapter
286
+ */
287
+ registerGateway(gateway: PaymentGatewayAdapter): void {
288
+ this.gateways.set(gateway.getName(), gateway);
289
+ console.log(`[PaymentGatewayManager] Registered gateway: ${gateway.getName()}`);
290
+ }
291
+
292
+ /**
293
+ * Get a registered gateway by name
294
+ */
295
+ getGateway(name: string): PaymentGatewayAdapter | undefined {
296
+ return this.gateways.get(name);
297
+ }
298
+
299
+ /**
300
+ * Get all registered gateway names
301
+ */
302
+ getGatewayNames(): string[] {
303
+ return Array.from(this.gateways.keys());
304
+ }
305
+
306
+ /**
307
+ * Check if a gateway is registered
308
+ */
309
+ hasGateway(name: string): boolean {
310
+ return this.gateways.has(name);
311
+ }
312
+
313
+ /**
314
+ * Create payment using specified gateway
315
+ */
316
+ async createPayment(gatewayName: string, request: PaymentRequest): Promise<PaymentResponse> {
317
+ const gateway = this.getGateway(gatewayName);
318
+ if (!gateway) {
319
+ return {
320
+ success: false,
321
+ error: `Gateway '${gatewayName}' not found`,
322
+ message: `Payment gateway '${gatewayName}' is not registered`
323
+ };
324
+ }
325
+
326
+ return await gateway.createPayment(request);
327
+ }
328
+
329
+ /**
330
+ * Verify payment using specified gateway
331
+ */
332
+ async verifyPayment(gatewayName: string, request: VerificationRequest): Promise<VerificationResponse> {
333
+ const gateway = this.getGateway(gatewayName);
334
+ if (!gateway) {
335
+ return {
336
+ success: false,
337
+ verified: false,
338
+ accessGranted: false,
339
+ error: `Gateway '${gatewayName}' not found`,
340
+ message: `Payment gateway '${gatewayName}' is not registered`
341
+ };
342
+ }
343
+
344
+ return await gateway.verifyPayment(request);
345
+ }
346
+ }