@solvapay/server 1.0.0-preview.5 → 1.0.0-preview.7

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.
package/README.md CHANGED
@@ -93,6 +93,36 @@ const result = await protectedHandler({
93
93
  });
94
94
  ```
95
95
 
96
+ ### Authentication Integration
97
+
98
+ You can integrate authentication adapters from `@solvapay/auth` with the `getCustomerRef` option:
99
+
100
+ ```ts
101
+ import { createSolvaPay } from '@solvapay/server';
102
+ import { SupabaseAuthAdapter } from '@solvapay/auth/supabase';
103
+
104
+ const auth = new SupabaseAuthAdapter({
105
+ jwtSecret: process.env.SUPABASE_JWT_SECRET!
106
+ });
107
+
108
+ const solvaPay = createSolvaPay({ apiKey: process.env.SOLVAPAY_SECRET_KEY! });
109
+
110
+ // Use with Next.js adapter
111
+ export const POST = solvaPay.payable({ agent: 'my-api' }).next(
112
+ async (args) => {
113
+ return { result: 'success' };
114
+ },
115
+ {
116
+ getCustomerRef: async (req) => {
117
+ const userId = await auth.getUserIdFromRequest(req);
118
+ return userId ?? 'anonymous';
119
+ }
120
+ }
121
+ );
122
+ ```
123
+
124
+ This automatically extracts the user ID from authentication tokens and uses it as the customer reference for paywall checks.
125
+
96
126
  ### When to Use Each Adapter
97
127
 
98
128
  Choose the adapter based on your context:
package/dist/edge.d.ts CHANGED
@@ -22,6 +22,62 @@ interface components {
22
22
  UpdatePlanRequest: Record<string, never>;
23
23
  ExecuteAnalyticsQuery: Record<string, never>;
24
24
  ExecuteMultipleQueries: Record<string, never>;
25
+ CreateCheckoutSessionRequest: {
26
+ /**
27
+ * @description Customer reference
28
+ * @example cus_3c4d5e6f7g8h
29
+ */
30
+ customerReference: string;
31
+ /**
32
+ * @description Plan reference (optional)
33
+ * @example pln_2b3c4d5e6f7g
34
+ */
35
+ planRef?: string;
36
+ /**
37
+ * @description Agent reference (optional)
38
+ * @example agt_1a2b3c4d5e6f
39
+ */
40
+ agentRef?: string;
41
+ };
42
+ CheckoutSessionResponse: {
43
+ /**
44
+ * @description Checkout session ID
45
+ * @example 507f1f77bcf86cd799439011
46
+ */
47
+ id: string;
48
+ /**
49
+ * @description Public session ID used in checkout URL
50
+ * @example a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
51
+ */
52
+ sessionId: string;
53
+ /**
54
+ * @description Amount in cents
55
+ * @example 2999
56
+ */
57
+ amount: number;
58
+ /**
59
+ * @description Currency code
60
+ * @example USD
61
+ */
62
+ currency: string;
63
+ /**
64
+ * @description Session status
65
+ * @example active
66
+ */
67
+ status: string;
68
+ /**
69
+ * @description Checkout URL to open the checkout page
70
+ * @example http://localhost:3000/customer/checkout?id=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
71
+ */
72
+ checkoutUrl: string;
73
+ };
74
+ CancelSubscriptionRequest: {
75
+ /**
76
+ * @description Reason for cancellation
77
+ * @example Customer request
78
+ */
79
+ reason?: string;
80
+ };
25
81
  CheckLimitRequest: {
26
82
  /**
27
83
  * @description Customer reference identifier
@@ -50,6 +106,11 @@ interface components {
50
106
  * @example https://checkout.solvapay.com/pay_1a2b3c4d
51
107
  */
52
108
  checkoutUrl?: string;
109
+ /**
110
+ * @description Optional checkout session ID if payment is required
111
+ * @example e3f1c2d4b6a89f001122334455667788
112
+ */
113
+ checkoutSessionId?: string;
53
114
  };
54
115
  UsageEvent: {
55
116
  /**
@@ -100,6 +161,11 @@ interface components {
100
161
  * @example John Doe
101
162
  */
102
163
  name?: string;
164
+ /**
165
+ * @description External reference ID from your auth system to map this customer to an auth user (optional)
166
+ * @example auth_user_12345
167
+ */
168
+ externalRef?: string;
103
169
  };
104
170
  SubscriptionInfo: {
105
171
  /**
@@ -144,6 +210,11 @@ interface components {
144
210
  * @example customer@example.com
145
211
  */
146
212
  email: string;
213
+ /**
214
+ * @description External reference ID from your auth system (if set during creation or update)
215
+ * @example auth_user_12345
216
+ */
217
+ externalRef?: string;
147
218
  /** @description Active subscriptions */
148
219
  subscriptions?: components["schemas"]["SubscriptionInfo"][];
149
220
  };
@@ -257,13 +328,6 @@ interface components {
257
328
  */
258
329
  createdAt: string;
259
330
  };
260
- CancelSubscriptionRequest: {
261
- /**
262
- * @description Reason for cancellation
263
- * @example Customer request
264
- */
265
- reason?: string;
266
- };
267
331
  CreatePageSettings: {
268
332
  /** @description Page identifier */
269
333
  id: string;
@@ -329,9 +393,30 @@ type CustomerResponseMapped = {
329
393
  customerRef: string;
330
394
  email?: string;
331
395
  name?: string;
396
+ externalRef?: string;
332
397
  plan?: string;
333
398
  subscriptions?: components['schemas']['SubscriptionInfo'][];
334
399
  };
400
+ /**
401
+ * Purchase information returned from payment processing
402
+ */
403
+ interface PurchaseInfo {
404
+ reference: string;
405
+ productRef?: string;
406
+ amount: number;
407
+ currency: string;
408
+ creditsAdded?: number;
409
+ completedAt: string;
410
+ }
411
+ /**
412
+ * Result from processing a payment intent
413
+ */
414
+ interface ProcessPaymentResult {
415
+ type: 'subscription' | 'purchase';
416
+ subscription?: components['schemas']['SubscriptionInfo'];
417
+ purchase?: PurchaseInfo;
418
+ status: 'completed';
419
+ }
335
420
  /**
336
421
  * SolvaPay API Client Interface
337
422
  *
@@ -350,6 +435,9 @@ interface SolvaPayClient {
350
435
  getCustomer?(params: {
351
436
  customerRef: string;
352
437
  }): Promise<CustomerResponseMapped>;
438
+ getCustomerByExternalRef?(params: {
439
+ externalRef: string;
440
+ }): Promise<CustomerResponseMapped>;
353
441
  listAgents?(): Promise<Array<{
354
442
  reference: string;
355
443
  name: string;
@@ -363,9 +451,14 @@ interface SolvaPayClient {
363
451
  listPlans?(agentRef: string): Promise<Array<{
364
452
  reference: string;
365
453
  name: string;
454
+ description?: string;
455
+ price?: number;
456
+ currency?: string;
457
+ interval?: string;
366
458
  isFreeTier?: boolean;
367
459
  freeUnits?: number;
368
- description?: string;
460
+ metadata?: Record<string, any>;
461
+ [key: string]: any;
369
462
  }>>;
370
463
  createPlan?(params: components['schemas']['CreatePlanRequest'] & {
371
464
  agentRef: string;
@@ -385,6 +478,16 @@ interface SolvaPayClient {
385
478
  publishableKey: string;
386
479
  accountId?: string;
387
480
  }>;
481
+ cancelSubscription?(params: {
482
+ subscriptionRef: string;
483
+ reason?: string;
484
+ }): Promise<components['schemas']['SubscriptionResponse']>;
485
+ processPayment?(params: {
486
+ paymentIntentId: string;
487
+ agentRef: string;
488
+ customerRef: string;
489
+ planRef?: string;
490
+ }): Promise<ProcessPaymentResult>;
388
491
  }
389
492
 
390
493
  /**
@@ -440,7 +543,7 @@ interface PaywallToolResult {
440
543
  /**
441
544
  * Retry configuration options
442
545
  */
443
- interface RetryOptions$1 {
546
+ interface RetryOptions {
444
547
  /**
445
548
  * Maximum number of retry attempts (default: 2)
446
549
  */
@@ -583,12 +686,6 @@ type ServerClientOptions = {
583
686
  */
584
687
  declare function createSolvaPayClient(opts: ServerClientOptions): SolvaPayClient;
585
688
 
586
- /**
587
- * SolvaPay Factory
588
- *
589
- * Main entry point for creating SolvaPay instances with the unified payable API
590
- */
591
-
592
689
  /**
593
690
  * Configuration for creating a SolvaPay instance
594
691
  */
@@ -639,8 +736,16 @@ interface SolvaPay {
639
736
  /**
640
737
  * Ensure customer exists (for testing/setup)
641
738
  * Only attempts creation once per customer (idempotent).
739
+ *
740
+ * @param customerRef - The customer reference (e.g., Supabase user ID)
741
+ * @param externalRef - Optional external reference for backend lookup (e.g., Supabase user ID)
742
+ * If provided, will lookup existing customer by externalRef before creating new one
743
+ * @param options - Optional customer details (email, name) for customer creation
642
744
  */
643
- ensureCustomer(customerRef: string): Promise<string>;
745
+ ensureCustomer(customerRef: string, externalRef?: string, options?: {
746
+ email?: string;
747
+ name?: string;
748
+ }): Promise<string>;
644
749
  /**
645
750
  * Create a payment intent for a customer to subscribe to a plan
646
751
  */
@@ -655,6 +760,16 @@ interface SolvaPay {
655
760
  publishableKey: string;
656
761
  accountId?: string;
657
762
  }>;
763
+ /**
764
+ * Process a payment intent after client-side confirmation
765
+ * Creates subscription or purchase immediately, eliminating webhook delay
766
+ */
767
+ processPayment(params: {
768
+ paymentIntentId: string;
769
+ agentRef: string;
770
+ customerRef: string;
771
+ planRef?: string;
772
+ }): Promise<ProcessPaymentResult>;
658
773
  /**
659
774
  * Check if customer is within usage limits
660
775
  */
@@ -716,12 +831,15 @@ interface SolvaPay {
716
831
  /**
717
832
  * Create a SolvaPay instance
718
833
  *
719
- * @param config - Configuration with either apiKey or apiClient
834
+ * @param config - Optional configuration with either apiKey or apiClient. If not provided, reads from environment variables.
720
835
  * @returns SolvaPay instance with payable() method
721
836
  *
722
837
  * @example
723
838
  * ```typescript
724
- * // Production: Pass API key
839
+ * // Production: Read from environment variables (recommended)
840
+ * const solvaPay = createSolvaPay();
841
+ *
842
+ * // Production: Pass API key explicitly
725
843
  * const solvaPay = createSolvaPay({
726
844
  * apiKey: process.env.SOLVAPAY_SECRET_KEY
727
845
  * });
@@ -737,7 +855,7 @@ interface SolvaPay {
737
855
  * export const POST = payable.next(createTask);
738
856
  * ```
739
857
  */
740
- declare function createSolvaPay(config: CreateSolvaPayConfig): SolvaPay;
858
+ declare function createSolvaPay(config?: CreateSolvaPayConfig): SolvaPay;
741
859
 
742
860
  /**
743
861
  * SolvaPay SDK - Universal Paywall Protection
@@ -756,39 +874,7 @@ declare class PaywallError extends Error {
756
874
  /**
757
875
  * Utility functions for the SolvaPay Server SDK
758
876
  */
759
- /**
760
- * Retry configuration options
761
- */
762
- interface RetryOptions {
763
- /**
764
- * Maximum number of retry attempts (default: 2)
765
- */
766
- maxRetries?: number;
767
- /**
768
- * Initial delay between retries in milliseconds (default: 500)
769
- */
770
- initialDelay?: number;
771
- /**
772
- * Backoff strategy for calculating delay between retries (default: 'fixed')
773
- * - 'fixed': Same delay between all retries
774
- * - 'linear': Delay increases linearly (initialDelay * attempt)
775
- * - 'exponential': Delay doubles each attempt (initialDelay * 2^(attempt-1))
776
- */
777
- backoffStrategy?: 'fixed' | 'linear' | 'exponential';
778
- /**
779
- * Optional function to determine if a retry should be attempted based on the error
780
- * @param error The error that was thrown
781
- * @param attempt The current attempt number (0-indexed)
782
- * @returns true if a retry should be attempted, false otherwise
783
- */
784
- shouldRetry?: (error: Error, attempt: number) => boolean;
785
- /**
786
- * Optional callback invoked before each retry attempt
787
- * @param error The error that triggered the retry
788
- * @param attempt The current attempt number (0-indexed)
789
- */
790
- onRetry?: (error: Error, attempt: number) => void;
791
- }
877
+
792
878
  /**
793
879
  * Executes an async function with automatic retry logic
794
880
  *
@@ -850,4 +936,4 @@ declare function verifyWebhook({ body, signature, secret }: {
850
936
  secret: string;
851
937
  }): Promise<any>;
852
938
 
853
- export { type CreateSolvaPayConfig, type HttpAdapterOptions, type McpAdapterOptions, type NextAdapterOptions, type PayableFunction, type PayableOptions, type PaywallArgs, PaywallError, type PaywallMetadata, type PaywallStructuredContent, type PaywallToolResult, type RetryOptions$1 as RetryOptions, type ServerClientOptions, type SolvaPay, type SolvaPayClient, createSolvaPay, createSolvaPayClient, verifyWebhook, withRetry };
939
+ export { type CreateSolvaPayConfig, type HttpAdapterOptions, type McpAdapterOptions, type NextAdapterOptions, type PayableFunction, type PayableOptions, type PaywallArgs, PaywallError, type PaywallMetadata, type PaywallStructuredContent, type PaywallToolResult, type RetryOptions, type ServerClientOptions, type SolvaPay, type SolvaPayClient, createSolvaPay, createSolvaPayClient, verifyWebhook, withRetry };