Documentation
SDK/Payments•7 min read

Payments

Accept payments and subscriptions, link purchases to customers, and verify payment updates.

Browse Docs

Payments

Managed payments let paid organizations accept one-time payments and monthly/yearly subscriptions in their applications. The seller completes Stripe-hosted onboarding; the platform provisions a scoped application credential. Your application never needs the platform’s Stripe key.

This API requires a platform deployment and SDK release that include managed payments. Test and live mode are separate.

One-time prices charge once. Recurring prices bill monthly or yearly until cancellation. Trials, usage-based billing and plan changes are outside this API.

Connect the seller

import { PHPSandbox } from '@phpsandbox/sdk';

const client = PHPSandbox.rest(platformToken);
const access = await client.payments.access();
const account = await client.payments.createAccount('test', 'DE');
const onboarding = await client.payments.onboarding('test');

Open onboarding.url for the organization administrator. On return, retrieve client.payments.accounts() and inspect chargesEnabled, payoutsEnabled and requirements. A return URL is not proof of verification.

Management uses payments:read, payments:manage and payments:refund permissions. Configuration also requires ownership of the sandbox and notebook write access. Organization membership alone does not grant financial permissions. Existing keys need explicit financial scopes.

Configure an application

const payments = client.payments.forNotebook('sandbox-id');
const resources = await client.payments.applications('sandbox-id');
// Let the administrator select one of resources.applications.
await payments.configure({ expectedRevision: 0, applicationId });
await payments.provision();
const price = await payments.createPrice({
  requestId: crypto.randomUUID(),
  name: 'Course',
  amount: 4900,
  currency: 'eur',
});
const review = await payments.prepareActivation();
// Present review.blockers, prices, readiness and fees before confirmation.
await payments.activate(review.reviewId);

All examples default to test mode. Pass 'live' explicitly for live configuration. Live activation requires a paid non-trial subscription, verified seller payment/payout readiness, configured platform fees and event verification, and a healthy application published after its live credential was provisioned. Editing configuration or adding a price invalidates older reviews and pauses collection.

The same methods are available as sandbox.payments. client.payments.forNotebook(id) does not fetch or start the sandbox, and does not require a browser-workspace project record.

Create checkout from the application server

Provisioning installs a shared app identity for Customers and Payments. The server client reads it automatically; development and production credentials remain separate. Production is selected when NODE_ENV=production, with no fallback to development. Test payments are available only in the development preview; published apps use Live payments. Runtimes without process.env can supply server bindings through { env }. Keep this client on the server.

const platform = PHPSandbox.app();
const runtime = platform.payments;
const checkout = await runtime.checkout({
  requestId: storedOrder.requestId,
  orderId: storedOrder.id,
  priceId: configuredPriceId,
  successPath: '/payment/success',
  cancelPath: '/course',
});

Create and authorize the order on your server first. Persist a stable UUID request ID and reuse it after timeouts. The server-owned price determines amount and currency. Redirect the buyer to checkout.checkoutUrl, but grant access only from verified server payment state. A browser redirect does not prove payment.

For non-TypeScript servers, POST /platform/payments/runtime/checkouts returns the transaction wrapped in data. An abbreviated response is:

{
  "data": {
    "id": "transaction-id",
    "orderId": "your-stored-order-id",
    "checkoutUrl": "https://checkout.example.com/session",
    "status": "pending"
  }
}

Store data.id as the transaction identity; checkout creation does not return a transactionId field. The SDK unwraps data, exposing checkout.id and checkout.checkoutUrl. Match HTTP test fixtures to this response contract.

To show purchases under a buyer’s Customers profile, pass customerId in the checkout request. Use the ID returned by platform.customers.identify(...), stored against the authenticated app account for the same app and environment:

const checkout = await runtime.checkout({
  requestId: storedOrder.requestId,
  orderId: storedOrder.id,
  priceId: configuredPriceId,
  customerId: authenticatedUser.phpsandboxCustomerId,
  successPath: '/payment/success',
  cancelPath: '/course',
});

The same optional field is supported by runtime.subscribe(...) and the checkout/subscription HTTP endpoints. Resolve the customer on your server rather than trusting an ID supplied by the browser. Omit customerId when the app does not need this association; accepting payments does not require using Customers. If linking is part of the intended behavior, verify the resulting purchase appears on the correct Test customer record.

For an existing unlinked one-time purchase, authorize the buyer against your stored order before attaching its customer:

await runtime.linkCustomer(storedOrder.transactionId, {
  orderId: storedOrder.id,
  customerId: authenticatedUser.phpsandboxCustomerId,
});

Check that your installed SDK provides linkCustomer. Other server runtimes can call PUT /platform/payments/runtime/transactions/:id/customer with { orderId, customerId }, authenticated with the same app credential. The operation requires a matching order and a customer in the same app and environment. It cannot replace an existing different customer or link a subscription transaction, and it creates no new payment. An activity event on a customer profile is separate from this payment relationship.

Verify updates and recover purchases

const event = await platform.payments.verifyEvent(rawBody, signatureHeader);

Read the original request body and phpsandbox-signature header before parsing or changing JSON. The SDK exports DEFAULT_PAYMENT_CALLBACK_PATH (/api/phpsandbox-payments/events) for new bindings. Saved callback paths remain unchanged unless explicitly overridden.

Store each order’s mode and require a verified event with that same mode; a test payment must never fulfil a live order.

In one database transaction, record the event’s unique id, locate your authenticated buyer’s order by event.transaction.orderId, verify the expected price/transaction identity, and apply only a newer transaction revision. Retry deliveries must not grant access twice. Ignore older revisions so an older paid update cannot undo a refund. Return a successful response only after committing fulfilment.

Use runtime.transaction(transactionId) for server-side reconciliation if a notification is delayed. Only show a purchase to its authenticated buyer. Never send the application credential to the browser.

Monthly and yearly subscriptions

Create a recurring offer with billingInterval: 'month' or 'year':

const price = await payments.createPrice({
  requestId: crypto.randomUUID(),
  name: 'Membership',
  amount: 1000,
  currency: 'eur',
  billingInterval: 'month',
});
// Review and activate the updated configuration before checkout.
const subscription = await runtime.subscribe({
  requestId: storedOrder.requestId,
  orderId: storedOrder.id,
  priceId: price.id,
  successPath: '/account',
  cancelPath: '/membership',
});

Store the subscription ID against the authenticated buyer’s order before redirecting to subscription.checkoutUrl. Stripe manages recurring collection. Each paid invoice becomes a transaction with subscriptionId, periodStart and periodEnd; fees use the percentage agreed when the subscription started.

verifyPaymentEvent() returns a discriminated union. Narrow on event.type: payment.updated contains transaction; subscription.updated contains subscription. Check the stored buyer order, price and subscription identity, deduplicate event IDs, and atomically apply only newer revisions. Grant membership access through the verified paidThrough date. An active status or checkout redirect alone is insufficient. Failed renewal does not extend paid access; successful recovery does.

const current = await runtime.subscription(storedOrder.subscriptionId);
const portal = await runtime.subscriptionPortal(current.id, { returnPath: '/account/billing' });
const canceled = await runtime.cancelSubscription(current.id);

Authorize these server routes against the authenticated buyer’s stored order. The hosted portal supports updating payment methods, viewing invoices and cancellation at period end; it does not enable plan changes. Cancellation preserves the paid period and does not refund payments. A refund’s invoice period lets the application distinguish a previous-period refund from its current membership payment.

Administrators can list subscriptions with payments.subscriptions(mode), reconcile one with payments.subscription(id, mode), cancel renewal with payments.cancelSubscription(id, mode), or create its portal with payments.subscriptionPortal(id, input, mode). Runtime methods are server-only and scoped to their application.

The reconciliation worker checks application availability as renewal approaches. An unavailable or no-longer-owned application has cancellation scheduled at period end rather than continuing renewal indefinitely. Repair or migrate the service before resuming new collection.

Refunds and access

const result = await payments.refund(transactionId, {
  requestId: storedRefundRequestId,
  amount: 2000,
});

Amounts are minor currency units. Omit amount to refund the remaining paid balance. The proportional platform fee is refunded too. result.refund.status distinguishes pending, required-action, failed, canceled and succeeded refunds; a pending refund is not money already returned. Use a stable request ID when retrying.

Your app must apply an explicit refund access policy. For example, retain course access after a partial refund and revoke it after a full refund. Observe the actual transaction refund status before changing access.

Pausing collection stops new checkouts while preserving existing subscription renewals, reconciliation, cancellation and refunds. Failed organization billing grants an already-paid organization a seven-day payment recovery window; afterward new collection and activation stop. Existing buyer subscriptions continue with their agreed platform fee. Persistent management keys expire with organization access; administrators retain web recovery access and buyer applications keep their scoped runtime recovery operations. Forks do not inherit payment credentials.

CLI

The CLI uses the same SDK methods:

phpsandbox payments status
phpsandbox payments connect --mode test --country DE
phpsandbox payments configure --sandbox sandbox-id --revision 0 --application application-id
phpsandbox payments provision --sandbox sandbox-id
phpsandbox payments prices create --sandbox sandbox-id --name Course --amount 4900 --currency eur --request-id stable-uuid
phpsandbox payments review --sandbox sandbox-id
phpsandbox payments activate --sandbox sandbox-id --review review-receipt
phpsandbox payments transactions --sandbox sandbox-id

Use --json for machine-readable output. Live activation requires --mode live --confirm-live; refunds require --yes. Keep request IDs stable across uncertain responses. Never place a payment token in a command argument or source file.