@phpsandbox/sdk 0.3.5 → 0.4.0

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/dist/index.d.ts CHANGED
@@ -18,6 +18,8 @@ import { PublicationApi } from './publication/index.js';
18
18
  import { ServerApi } from './servers.js';
19
19
  import { Feedback } from './feedback.js';
20
20
  import { IntegrationApi, SandboxIntegrationApi } from './integrations/index.js';
21
+ import { PaymentsApi, NotebookPayments } from './payments.js';
22
+ export * from './payments.js';
21
23
  export type { Disposable } from './types.js';
22
24
  export { LspConnection } from './lsp.js';
23
25
  export { FileChangeFilter, FileChangeType, FileType } from './filesystem.js';
@@ -329,6 +331,7 @@ declare class ClientImplementation {
329
331
  readonly publications: PublicationApi;
330
332
  readonly servers: ServerApi;
331
333
  readonly integrations: IntegrationApi;
334
+ readonly payments: PaymentsApi;
332
335
  readonly options: PHPSandboxClientOptions;
333
336
  private readonly runtimeTransportValue;
334
337
  get runtimeTransport(): RuntimeTransport;
@@ -364,6 +367,7 @@ export declare class PHPSandbox {
364
367
  readonly publications: PublicationApi;
365
368
  readonly servers: ServerApi;
366
369
  readonly integrations: IntegrationApi;
370
+ readonly payments: PaymentsApi;
367
371
  private constructor();
368
372
  whoami(): Promise<Identity>;
369
373
  get runtimeTransport(): RuntimeTransport;
@@ -399,6 +403,7 @@ export declare class NotebookInstance {
399
403
  readonly config: Config;
400
404
  readonly secrets: NotebookSecrets;
401
405
  readonly integrations: SandboxIntegrationApi;
406
+ readonly payments: NotebookPayments;
402
407
  readonly preview: NotebookPreview;
403
408
  readonly mail: NotebookMail;
404
409
  readonly feedback: Feedback;
package/dist/index.js CHANGED
@@ -31,6 +31,8 @@ import { RestRuntimeInvoker } from './runtime/rest.js';
31
31
  import { Feedback } from './feedback.js';
32
32
  import { IntegrationApi, SandboxIntegrationApi } from './integrations/index.js';
33
33
  import { authenticatedRequest } from './http.js';
34
+ import { PaymentsApi, NotebookPayments } from './payments.js';
35
+ export * from './payments.js';
34
36
  export { LspConnection } from './lsp.js';
35
37
  export { FileChangeFilter, FileChangeType, FileType } from './filesystem.js';
36
38
  export { notebookBuiltinServices, notebookKnownServices } from './services.js';
@@ -86,6 +88,7 @@ class ClientImplementation {
86
88
  this.notebook = new NotebookApi(this);
87
89
  this.servers = new ServerApi(this);
88
90
  this.integrations = new IntegrationApi(this);
91
+ this.payments = new PaymentsApi(this);
89
92
  this.options = { ...options };
90
93
  this.runtimeTransportValue = runtimeTransport;
91
94
  this.baseUrl = normalizeApiBaseUrl(url);
@@ -220,6 +223,7 @@ export class PHPSandbox {
220
223
  this.publications = client.publications;
221
224
  this.servers = client.servers;
222
225
  this.integrations = client.integrations;
226
+ this.payments = client.payments;
223
227
  }
224
228
  async whoami() {
225
229
  const { data } = await this.client.get('/auth/whoami');
@@ -287,6 +291,7 @@ export class NotebookInstance {
287
291
  this.config = new Config(this);
288
292
  this.secrets = new NotebookSecrets(client, this.data.id);
289
293
  this.integrations = new SandboxIntegrationApi(this.data.id, client);
294
+ this.payments = new NotebookPayments(this.data.id, client);
290
295
  this.preview = new NotebookPreview(client, this.data.id);
291
296
  this.mail = new NotebookMail(client, this.data.id);
292
297
  this.feedback = new Feedback(client, this.data.id);
@@ -0,0 +1,347 @@
1
+ import { z } from 'zod';
2
+ import type { Client } from './index.js';
3
+ export declare const DEFAULT_PAYMENT_CALLBACK_PATH = "/api/phpsandbox-payments/events";
4
+ export declare const paymentModeSchema: z.ZodEnum<{
5
+ test: "test";
6
+ live: "live";
7
+ }>;
8
+ export type PaymentMode = z.infer<typeof paymentModeSchema>;
9
+ declare const accountSchema: z.ZodObject<{
10
+ id: z.ZodString;
11
+ mode: z.ZodEnum<{
12
+ test: "test";
13
+ live: "live";
14
+ }>;
15
+ chargesEnabled: z.ZodBoolean;
16
+ payoutsEnabled: z.ZodBoolean;
17
+ detailsSubmitted: z.ZodBoolean;
18
+ requirements: z.ZodArray<z.ZodString>;
19
+ disabledReason: z.ZodNullable<z.ZodString>;
20
+ }, z.core.$strip>;
21
+ export type PaymentAccountData = z.infer<typeof accountSchema>;
22
+ declare const accessSchema: z.ZodObject<{
23
+ subscribed: z.ZodBoolean;
24
+ liveAllowed: z.ZodBoolean;
25
+ testConfigured: z.ZodBoolean;
26
+ liveConfigured: z.ZodBoolean;
27
+ feeBasisPoints: z.ZodNullable<z.ZodNumber>;
28
+ canRead: z.ZodBoolean;
29
+ canManage: z.ZodBoolean;
30
+ canRefund: z.ZodBoolean;
31
+ recoveryEndsAt: z.ZodDefault<z.ZodNullable<z.ZodString>>;
32
+ }, z.core.$strip>;
33
+ export type PaymentsAccess = z.infer<typeof accessSchema>;
34
+ declare const applicationsSchema: z.ZodObject<{
35
+ notebookId: z.ZodString;
36
+ applications: z.ZodArray<z.ZodObject<{
37
+ id: z.ZodString;
38
+ url: z.ZodNullable<z.ZodString>;
39
+ healthy: z.ZodBoolean;
40
+ passwordProtected: z.ZodBoolean;
41
+ deployedAt: z.ZodNullable<z.ZodString>;
42
+ }, z.core.$strip>>;
43
+ }, z.core.$strip>;
44
+ export type PaymentApplicationsData = z.infer<typeof applicationsSchema>;
45
+ declare const bindingSchema: z.ZodObject<{
46
+ id: z.ZodString;
47
+ notebookId: z.ZodString;
48
+ applicationId: z.ZodNullable<z.ZodString>;
49
+ mode: z.ZodEnum<{
50
+ test: "test";
51
+ live: "live";
52
+ }>;
53
+ revision: z.ZodNumber;
54
+ accountId: z.ZodString;
55
+ enabled: z.ZodBoolean;
56
+ callbackUrl: z.ZodNullable<z.ZodString>;
57
+ originUrl: z.ZodNullable<z.ZodString>;
58
+ runtimeConfigured: z.ZodBoolean;
59
+ }, z.core.$strip>;
60
+ export type PaymentBindingData = z.infer<typeof bindingSchema>;
61
+ declare const priceSchema: z.ZodObject<{
62
+ billingInterval: z.ZodDefault<z.ZodNullable<z.ZodEnum<{
63
+ month: "month";
64
+ year: "year";
65
+ }>>>;
66
+ id: z.ZodString;
67
+ name: z.ZodString;
68
+ amount: z.ZodNumber;
69
+ currency: z.ZodString;
70
+ bindingId: z.ZodString;
71
+ }, z.core.$strip>;
72
+ export type PaymentPriceData = z.infer<typeof priceSchema>;
73
+ declare const transactionSchema: z.ZodObject<{
74
+ subscriptionId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
75
+ periodStart: z.ZodDefault<z.ZodNullable<z.ZodString>>;
76
+ periodEnd: z.ZodDefault<z.ZodNullable<z.ZodString>>;
77
+ id: z.ZodString;
78
+ bindingId: z.ZodString;
79
+ orderId: z.ZodString;
80
+ priceId: z.ZodString;
81
+ amount: z.ZodNumber;
82
+ currency: z.ZodString;
83
+ feeAmount: z.ZodNumber;
84
+ revision: z.ZodNumber;
85
+ refundedAmount: z.ZodNumber;
86
+ status: z.ZodEnum<{
87
+ pending: "pending";
88
+ failed: "failed";
89
+ paid: "paid";
90
+ refunded: "refunded";
91
+ partially_refunded: "partially_refunded";
92
+ }>;
93
+ checkoutUrl: z.ZodNullable<z.ZodString>;
94
+ deliveredAt: z.ZodNullable<z.ZodString>;
95
+ }, z.core.$strip>;
96
+ export type PaymentTransactionData = z.infer<typeof transactionSchema>;
97
+ declare const subscriptionSchema: z.ZodObject<{
98
+ id: z.ZodString;
99
+ bindingId: z.ZodString;
100
+ priceId: z.ZodString;
101
+ orderId: z.ZodString;
102
+ status: z.ZodEnum<{
103
+ pending: "pending";
104
+ incomplete: "incomplete";
105
+ incomplete_expired: "incomplete_expired";
106
+ trialing: "trialing";
107
+ active: "active";
108
+ past_due: "past_due";
109
+ canceled: "canceled";
110
+ unpaid: "unpaid";
111
+ paused: "paused";
112
+ }>;
113
+ billingInterval: z.ZodEnum<{
114
+ month: "month";
115
+ year: "year";
116
+ }>;
117
+ paidThrough: z.ZodNullable<z.ZodString>;
118
+ cancelAtPeriodEnd: z.ZodBoolean;
119
+ checkoutUrl: z.ZodNullable<z.ZodString>;
120
+ revision: z.ZodNumber;
121
+ }, z.core.$strip>;
122
+ export type PaymentSubscriptionData = z.infer<typeof subscriptionSchema>;
123
+ export interface PaymentSubscriptionPortalInput {
124
+ returnPath: string;
125
+ }
126
+ declare const refundResultSchema: z.ZodObject<{
127
+ subscriptionId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
128
+ periodStart: z.ZodDefault<z.ZodNullable<z.ZodString>>;
129
+ periodEnd: z.ZodDefault<z.ZodNullable<z.ZodString>>;
130
+ id: z.ZodString;
131
+ bindingId: z.ZodString;
132
+ orderId: z.ZodString;
133
+ priceId: z.ZodString;
134
+ amount: z.ZodNumber;
135
+ currency: z.ZodString;
136
+ feeAmount: z.ZodNumber;
137
+ revision: z.ZodNumber;
138
+ refundedAmount: z.ZodNumber;
139
+ status: z.ZodEnum<{
140
+ pending: "pending";
141
+ failed: "failed";
142
+ paid: "paid";
143
+ refunded: "refunded";
144
+ partially_refunded: "partially_refunded";
145
+ }>;
146
+ checkoutUrl: z.ZodNullable<z.ZodString>;
147
+ deliveredAt: z.ZodNullable<z.ZodString>;
148
+ refund: z.ZodObject<{
149
+ id: z.ZodString;
150
+ amount: z.ZodNumber;
151
+ status: z.ZodEnum<{
152
+ pending: "pending";
153
+ failed: "failed";
154
+ succeeded: "succeeded";
155
+ canceled: "canceled";
156
+ requires_action: "requires_action";
157
+ }>;
158
+ }, z.core.$strip>;
159
+ }, z.core.$strip>;
160
+ export type PaymentRefundResult = z.infer<typeof refundResultSchema>;
161
+ declare const activationSchema: z.ZodObject<{
162
+ revision: z.ZodNumber;
163
+ reviewId: z.ZodString;
164
+ expiresAt: z.ZodString;
165
+ blockers: z.ZodArray<z.ZodString>;
166
+ binding: z.ZodObject<{
167
+ id: z.ZodString;
168
+ notebookId: z.ZodString;
169
+ applicationId: z.ZodNullable<z.ZodString>;
170
+ mode: z.ZodEnum<{
171
+ test: "test";
172
+ live: "live";
173
+ }>;
174
+ revision: z.ZodNumber;
175
+ accountId: z.ZodString;
176
+ enabled: z.ZodBoolean;
177
+ callbackUrl: z.ZodNullable<z.ZodString>;
178
+ originUrl: z.ZodNullable<z.ZodString>;
179
+ runtimeConfigured: z.ZodBoolean;
180
+ }, z.core.$strip>;
181
+ account: z.ZodObject<{
182
+ id: z.ZodString;
183
+ mode: z.ZodEnum<{
184
+ test: "test";
185
+ live: "live";
186
+ }>;
187
+ chargesEnabled: z.ZodBoolean;
188
+ payoutsEnabled: z.ZodBoolean;
189
+ detailsSubmitted: z.ZodBoolean;
190
+ requirements: z.ZodArray<z.ZodString>;
191
+ disabledReason: z.ZodNullable<z.ZodString>;
192
+ }, z.core.$strip>;
193
+ feeBasisPoints: z.ZodNullable<z.ZodNumber>;
194
+ prices: z.ZodArray<z.ZodObject<{
195
+ billingInterval: z.ZodDefault<z.ZodNullable<z.ZodEnum<{
196
+ month: "month";
197
+ year: "year";
198
+ }>>>;
199
+ id: z.ZodString;
200
+ name: z.ZodString;
201
+ amount: z.ZodNumber;
202
+ currency: z.ZodString;
203
+ bindingId: z.ZodString;
204
+ }, z.core.$strip>>;
205
+ }, z.core.$strip>;
206
+ export type PaymentActivationReview = z.infer<typeof activationSchema>;
207
+ export interface ConfigurePaymentsInput {
208
+ expectedRevision: number;
209
+ applicationId?: string | null;
210
+ callbackPath?: string;
211
+ }
212
+ export interface CreatePaymentPriceInput {
213
+ billingInterval?: 'month' | 'year';
214
+ requestId: string;
215
+ name: string;
216
+ amount: number;
217
+ currency: string;
218
+ }
219
+ export interface CreatePaymentCheckoutInput {
220
+ requestId: string;
221
+ orderId: string;
222
+ priceId: string;
223
+ successPath: string;
224
+ cancelPath: string;
225
+ }
226
+ export interface RefundPaymentInput {
227
+ requestId: string;
228
+ amount?: number;
229
+ }
230
+ export declare class PaymentsApi {
231
+ private readonly client;
232
+ readonly runtime: PaymentRuntime;
233
+ constructor(client: Client);
234
+ forNotebook(notebookId: string): NotebookPayments;
235
+ applications(notebookId: string): Promise<PaymentApplicationsData>;
236
+ access(): Promise<PaymentsAccess>;
237
+ accounts(): Promise<PaymentAccountData[]>;
238
+ createAccount(mode: PaymentMode, country?: string): Promise<PaymentAccountData>;
239
+ onboarding(mode: PaymentMode): Promise<{
240
+ url: string;
241
+ expiresAt: string;
242
+ }>;
243
+ }
244
+ export declare class NotebookPayments {
245
+ private readonly notebookId;
246
+ private readonly client;
247
+ constructor(notebookId: string, client: Client);
248
+ private path;
249
+ get(mode?: PaymentMode): Promise<PaymentBindingData | null>;
250
+ configure(input: ConfigurePaymentsInput, mode?: PaymentMode): Promise<PaymentBindingData>;
251
+ provision(mode?: PaymentMode): Promise<PaymentBindingData>;
252
+ prices(mode?: PaymentMode): Promise<PaymentPriceData[]>;
253
+ createPrice(input: CreatePaymentPriceInput, mode?: PaymentMode): Promise<PaymentPriceData>;
254
+ prepareActivation(mode?: PaymentMode): Promise<PaymentActivationReview>;
255
+ activate(reviewId: string, mode?: PaymentMode): Promise<PaymentBindingData>;
256
+ disable(mode?: PaymentMode): Promise<PaymentBindingData>;
257
+ checkout(input: CreatePaymentCheckoutInput, mode?: PaymentMode): Promise<PaymentTransactionData>;
258
+ subscribe(input: CreatePaymentCheckoutInput, mode?: PaymentMode): Promise<PaymentSubscriptionData>;
259
+ subscriptions(mode?: PaymentMode): Promise<PaymentSubscriptionData[]>;
260
+ subscription(id: string, mode?: PaymentMode): Promise<PaymentSubscriptionData>;
261
+ cancelSubscription(id: string, mode?: PaymentMode): Promise<PaymentSubscriptionData>;
262
+ subscriptionPortal(id: string, input: PaymentSubscriptionPortalInput, mode?: PaymentMode): Promise<{
263
+ url: string;
264
+ }>;
265
+ transactions(mode?: PaymentMode): Promise<PaymentTransactionData[]>;
266
+ refund(id: string, input: RefundPaymentInput, mode?: PaymentMode): Promise<PaymentRefundResult>;
267
+ }
268
+ declare const paymentEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
269
+ id: z.ZodString;
270
+ type: z.ZodLiteral<"payment.updated">;
271
+ mode: z.ZodEnum<{
272
+ test: "test";
273
+ live: "live";
274
+ }>;
275
+ transaction: z.ZodObject<{
276
+ subscriptionId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
277
+ periodStart: z.ZodDefault<z.ZodNullable<z.ZodString>>;
278
+ periodEnd: z.ZodDefault<z.ZodNullable<z.ZodString>>;
279
+ id: z.ZodString;
280
+ bindingId: z.ZodString;
281
+ orderId: z.ZodString;
282
+ priceId: z.ZodString;
283
+ amount: z.ZodNumber;
284
+ currency: z.ZodString;
285
+ feeAmount: z.ZodNumber;
286
+ revision: z.ZodNumber;
287
+ refundedAmount: z.ZodNumber;
288
+ status: z.ZodEnum<{
289
+ pending: "pending";
290
+ failed: "failed";
291
+ paid: "paid";
292
+ refunded: "refunded";
293
+ partially_refunded: "partially_refunded";
294
+ }>;
295
+ checkoutUrl: z.ZodNullable<z.ZodString>;
296
+ deliveredAt: z.ZodNullable<z.ZodString>;
297
+ }, z.core.$strip>;
298
+ }, z.core.$strip>, z.ZodObject<{
299
+ id: z.ZodString;
300
+ type: z.ZodLiteral<"subscription.updated">;
301
+ mode: z.ZodEnum<{
302
+ test: "test";
303
+ live: "live";
304
+ }>;
305
+ subscription: z.ZodObject<{
306
+ id: z.ZodString;
307
+ bindingId: z.ZodString;
308
+ priceId: z.ZodString;
309
+ orderId: z.ZodString;
310
+ status: z.ZodEnum<{
311
+ pending: "pending";
312
+ incomplete: "incomplete";
313
+ incomplete_expired: "incomplete_expired";
314
+ trialing: "trialing";
315
+ active: "active";
316
+ past_due: "past_due";
317
+ canceled: "canceled";
318
+ unpaid: "unpaid";
319
+ paused: "paused";
320
+ }>;
321
+ billingInterval: z.ZodEnum<{
322
+ month: "month";
323
+ year: "year";
324
+ }>;
325
+ paidThrough: z.ZodNullable<z.ZodString>;
326
+ cancelAtPeriodEnd: z.ZodBoolean;
327
+ checkoutUrl: z.ZodNullable<z.ZodString>;
328
+ revision: z.ZodNumber;
329
+ }, z.core.$strip>;
330
+ }, z.core.$strip>], "type">;
331
+ export type PaymentEvent = z.infer<typeof paymentEventSchema>;
332
+ /** Verify the original bytes before parsing JSON. Use only in trusted server code. */
333
+ export declare function verifyPaymentEvent(body: string, signature: string, token: string, mode: PaymentMode, now?: number): Promise<PaymentEvent>;
334
+ export declare class PaymentRuntime {
335
+ private readonly client;
336
+ constructor(client: Client);
337
+ checkout(input: CreatePaymentCheckoutInput): Promise<PaymentTransactionData>;
338
+ transaction(id: string): Promise<PaymentTransactionData>;
339
+ subscribe(input: CreatePaymentCheckoutInput): Promise<PaymentSubscriptionData>;
340
+ subscription(id: string): Promise<PaymentSubscriptionData>;
341
+ cancelSubscription(id: string): Promise<PaymentSubscriptionData>;
342
+ subscriptionPortal(id: string, input: PaymentSubscriptionPortalInput): Promise<{
343
+ url: string;
344
+ }>;
345
+ prices(): Promise<PaymentPriceData[]>;
346
+ }
347
+ export {};
@@ -0,0 +1,256 @@
1
+ import { z } from 'zod';
2
+ export const DEFAULT_PAYMENT_CALLBACK_PATH = '/api/phpsandbox-payments/events';
3
+ export const paymentModeSchema = z.enum(['test', 'live']);
4
+ const accountSchema = z.object({
5
+ id: z.string(),
6
+ mode: paymentModeSchema,
7
+ chargesEnabled: z.boolean(),
8
+ payoutsEnabled: z.boolean(),
9
+ detailsSubmitted: z.boolean(),
10
+ requirements: z.array(z.string()),
11
+ disabledReason: z.string().nullable(),
12
+ });
13
+ const accessSchema = z.object({
14
+ subscribed: z.boolean(),
15
+ liveAllowed: z.boolean(),
16
+ testConfigured: z.boolean(),
17
+ liveConfigured: z.boolean(),
18
+ feeBasisPoints: z.number().int().min(0).max(10000).nullable(),
19
+ canRead: z.boolean(),
20
+ canManage: z.boolean(),
21
+ canRefund: z.boolean(),
22
+ recoveryEndsAt: z.string().nullable().default(null),
23
+ });
24
+ const applicationsSchema = z.object({
25
+ notebookId: z.string(),
26
+ applications: z.array(z.object({
27
+ id: z.string(),
28
+ url: z.string().nullable(),
29
+ healthy: z.boolean(),
30
+ passwordProtected: z.boolean(),
31
+ deployedAt: z.string().datetime().nullable(),
32
+ })),
33
+ });
34
+ const bindingSchema = z.object({
35
+ id: z.string(),
36
+ notebookId: z.string(),
37
+ applicationId: z.string().nullable(),
38
+ mode: paymentModeSchema,
39
+ revision: z.number().int(),
40
+ accountId: z.string(),
41
+ enabled: z.boolean(),
42
+ callbackUrl: z.string().nullable(),
43
+ originUrl: z.string().nullable(),
44
+ runtimeConfigured: z.boolean(),
45
+ });
46
+ const priceSchema = z.object({
47
+ billingInterval: z.enum(['month', 'year']).nullable().default(null),
48
+ id: z.string(),
49
+ name: z.string(),
50
+ amount: z.number().int(),
51
+ currency: z.string(),
52
+ bindingId: z.string(),
53
+ });
54
+ const transactionSchema = z.object({
55
+ subscriptionId: z.string().nullable().default(null),
56
+ periodStart: z.string().datetime({ offset: true }).nullable().default(null),
57
+ periodEnd: z.string().datetime({ offset: true }).nullable().default(null),
58
+ id: z.string(),
59
+ bindingId: z.string(),
60
+ orderId: z.string(),
61
+ priceId: z.string(),
62
+ amount: z.number().int(),
63
+ currency: z.string(),
64
+ feeAmount: z.number().int(),
65
+ revision: z.number().int(),
66
+ refundedAmount: z.number().int(),
67
+ status: z.enum(['pending', 'paid', 'failed', 'refunded', 'partially_refunded']),
68
+ checkoutUrl: z.string().nullable(),
69
+ deliveredAt: z.string().nullable(),
70
+ });
71
+ const subscriptionSchema = z.object({
72
+ id: z.string(),
73
+ bindingId: z.string(),
74
+ priceId: z.string(),
75
+ orderId: z.string(),
76
+ status: z.enum([
77
+ 'pending',
78
+ 'incomplete',
79
+ 'incomplete_expired',
80
+ 'trialing',
81
+ 'active',
82
+ 'past_due',
83
+ 'canceled',
84
+ 'unpaid',
85
+ 'paused',
86
+ ]),
87
+ billingInterval: z.enum(['month', 'year']),
88
+ paidThrough: z.string().datetime({ offset: true }).nullable(),
89
+ cancelAtPeriodEnd: z.boolean(),
90
+ checkoutUrl: z.string().nullable(),
91
+ revision: z.number().int(),
92
+ });
93
+ const portalSchema = z.object({ url: z.string().url() });
94
+ const refundResultSchema = transactionSchema.extend({
95
+ refund: z.object({
96
+ id: z.string(),
97
+ amount: z.number().int().positive(),
98
+ status: z.enum(['pending', 'succeeded', 'failed', 'canceled', 'requires_action']),
99
+ }),
100
+ });
101
+ const activationSchema = z.object({
102
+ revision: z.number().int(),
103
+ reviewId: z.string(),
104
+ expiresAt: z.string(),
105
+ blockers: z.array(z.string()),
106
+ binding: bindingSchema,
107
+ account: accountSchema,
108
+ feeBasisPoints: z.number().int().nullable(),
109
+ prices: z.array(priceSchema),
110
+ });
111
+ export class PaymentsApi {
112
+ constructor(client) {
113
+ this.client = client;
114
+ this.runtime = new PaymentRuntime(client);
115
+ }
116
+ forNotebook(notebookId) {
117
+ return new NotebookPayments(notebookId, this.client);
118
+ }
119
+ async applications(notebookId) {
120
+ return applicationsSchema.parse((await this.client.get(`/notebook/${encodeURIComponent(notebookId)}/payments/applications`)).data);
121
+ }
122
+ async access() {
123
+ return accessSchema.parse((await this.client.get('/platform/payments/access')).data);
124
+ }
125
+ async accounts() {
126
+ return z.array(accountSchema).parse((await this.client.get('/platform/payments/accounts')).data);
127
+ }
128
+ async createAccount(mode, country) {
129
+ return accountSchema.parse((await this.client.put(`/platform/payments/accounts/${mode}`, { country })).data);
130
+ }
131
+ async onboarding(mode) {
132
+ return z
133
+ .object({ url: z.string().url(), expiresAt: z.string() })
134
+ .parse((await this.client.post(`/platform/payments/accounts/${mode}/onboarding`, {})).data);
135
+ }
136
+ }
137
+ export class NotebookPayments {
138
+ constructor(notebookId, client) {
139
+ this.notebookId = notebookId;
140
+ this.client = client;
141
+ }
142
+ path(mode) {
143
+ return `/platform/payments/sandboxes/${encodeURIComponent(this.notebookId)}/${mode}`;
144
+ }
145
+ async get(mode = 'test') {
146
+ return bindingSchema.nullable().parse((await this.client.get(this.path(mode))).data);
147
+ }
148
+ async configure(input, mode = 'test') {
149
+ return bindingSchema.parse((await this.client.put(this.path(mode), input)).data);
150
+ }
151
+ async provision(mode = 'test') {
152
+ return bindingSchema.parse((await this.client.post(`${this.path(mode)}/provision`, {})).data);
153
+ }
154
+ async prices(mode = 'test') {
155
+ return z.array(priceSchema).parse((await this.client.get(`${this.path(mode)}/prices`)).data);
156
+ }
157
+ async createPrice(input, mode = 'test') {
158
+ return priceSchema.parse((await this.client.post(`${this.path(mode)}/prices`, input)).data);
159
+ }
160
+ async prepareActivation(mode = 'test') {
161
+ return activationSchema.parse((await this.client.post(`${this.path(mode)}/activation`, {})).data);
162
+ }
163
+ async activate(reviewId, mode = 'test') {
164
+ return bindingSchema.parse((await this.client.post(`${this.path(mode)}/activate`, { reviewId })).data);
165
+ }
166
+ async disable(mode = 'test') {
167
+ return bindingSchema.parse((await this.client.post(`${this.path(mode)}/disable`, {})).data);
168
+ }
169
+ async checkout(input, mode = 'test') {
170
+ return transactionSchema.parse((await this.client.post(`${this.path(mode)}/checkouts`, input)).data);
171
+ }
172
+ async subscribe(input, mode = 'test') {
173
+ return subscriptionSchema.parse((await this.client.post(`${this.path(mode)}/subscriptions`, input)).data);
174
+ }
175
+ async subscriptions(mode = 'test') {
176
+ return z.array(subscriptionSchema).parse((await this.client.get(`${this.path(mode)}/subscriptions`)).data);
177
+ }
178
+ async subscription(id, mode = 'test') {
179
+ return subscriptionSchema.parse((await this.client.get(`${this.path(mode)}/subscriptions/${encodeURIComponent(id)}`)).data);
180
+ }
181
+ async cancelSubscription(id, mode = 'test') {
182
+ return subscriptionSchema.parse((await this.client.post(`${this.path(mode)}/subscriptions/${encodeURIComponent(id)}/cancel`, {})).data);
183
+ }
184
+ async subscriptionPortal(id, input, mode = 'test') {
185
+ return portalSchema.parse((await this.client.post(`${this.path(mode)}/subscriptions/${encodeURIComponent(id)}/portal`, input)).data);
186
+ }
187
+ async transactions(mode = 'test') {
188
+ return z.array(transactionSchema).parse((await this.client.get(`${this.path(mode)}/transactions`)).data);
189
+ }
190
+ async refund(id, input, mode = 'test') {
191
+ return refundResultSchema.parse((await this.client.post(`${this.path(mode)}/transactions/${encodeURIComponent(id)}/refund`, input)).data);
192
+ }
193
+ }
194
+ const paymentEventSchema = z.discriminatedUnion('type', [
195
+ z.object({
196
+ id: z.string(),
197
+ type: z.literal('payment.updated'),
198
+ mode: paymentModeSchema,
199
+ transaction: transactionSchema,
200
+ }),
201
+ z.object({
202
+ id: z.string(),
203
+ type: z.literal('subscription.updated'),
204
+ mode: paymentModeSchema,
205
+ subscription: subscriptionSchema,
206
+ }),
207
+ ]);
208
+ /** Verify the original bytes before parsing JSON. Use only in trusted server code. */
209
+ export async function verifyPaymentEvent(body, signature, token, mode, now = Date.now()) {
210
+ if (!/^hpay_[a-f0-9]{64}$/.test(token)) {
211
+ throw new Error('Invalid application payment credential.');
212
+ }
213
+ const match = /^t=(\d+),v1=([a-f0-9]{64})$/.exec(signature);
214
+ const timestamp = match?.[1];
215
+ const digest = match?.[2];
216
+ if (!timestamp || !digest || Math.abs(now - Number(timestamp) * 1000) > 300000 || body.length > 262144) {
217
+ throw new Error('Invalid or expired payment signature.');
218
+ }
219
+ const encoder = new TextEncoder();
220
+ const key = await crypto.subtle.importKey('raw', encoder.encode(token), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
221
+ const bytes = Uint8Array.from(digest.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16));
222
+ if (!(await crypto.subtle.verify('HMAC', key, bytes, encoder.encode(`${timestamp}.${body}`)))) {
223
+ throw new Error('Invalid payment signature.');
224
+ }
225
+ const event = paymentEventSchema.parse(JSON.parse(body));
226
+ if (event.mode !== mode) {
227
+ throw new Error('Payment event mode does not match this application.');
228
+ }
229
+ return event;
230
+ }
231
+ export class PaymentRuntime {
232
+ constructor(client) {
233
+ this.client = client;
234
+ }
235
+ async checkout(input) {
236
+ return transactionSchema.parse((await this.client.post('/platform/payments/runtime/checkouts', input)).data);
237
+ }
238
+ async transaction(id) {
239
+ return transactionSchema.parse((await this.client.get(`/platform/payments/runtime/transactions/${encodeURIComponent(id)}`)).data);
240
+ }
241
+ async subscribe(input) {
242
+ return subscriptionSchema.parse((await this.client.post('/platform/payments/runtime/subscriptions', input)).data);
243
+ }
244
+ async subscription(id) {
245
+ return subscriptionSchema.parse((await this.client.get(`/platform/payments/runtime/subscriptions/${encodeURIComponent(id)}`)).data);
246
+ }
247
+ async cancelSubscription(id) {
248
+ return subscriptionSchema.parse((await this.client.post(`/platform/payments/runtime/subscriptions/${encodeURIComponent(id)}/cancel`, {})).data);
249
+ }
250
+ async subscriptionPortal(id, input) {
251
+ return portalSchema.parse((await this.client.post(`/platform/payments/runtime/subscriptions/${encodeURIComponent(id)}/portal`, input)).data);
252
+ }
253
+ async prices() {
254
+ return z.array(priceSchema).parse((await this.client.get('/platform/payments/runtime/prices')).data);
255
+ }
256
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phpsandbox/sdk",
3
- "version": "0.3.5",
3
+ "version": "0.4.0",
4
4
  "description": "The TypeScript SDK for PHPSandbox cloud development environments",
5
5
  "keywords": [
6
6
  "cloud",