Skip to content

Stripe Integration

Purpose

Stripe Integration connects existing Subscrio customers and billing cycles to Stripe. It creates Checkout sessions and applies supported webhook events. Your application owns webhook delivery, signature verification, and duplicate-event handling.

Access and initialization

Access

const stripe = subscrio.stripe;
var stripe = subscrio.Stripe;

Configure Stripe credentials on Subscrio. Checkout needs a secret key and a billing cycle whose external product ID is a Stripe price ID. Webhook processing accepts a verified event.

Method catalog

Method Purpose
createCheckoutSession Creates a hosted Checkout session.
constructStripeEvent Verifies a webhook signature and parses the event.
processStripeEvent Applies a verified event.
createStripeSubscription Deprecated; always throws.
Method Purpose
CreateCheckoutSessionAsync Creates a hosted Checkout session.
Signature verification No Subscrio method; use Stripe EventUtility.
ProcessStripeEventAsync Applies a verified event.
CreateStripeSubscriptionAsync Obsolete; always throws.

Method details

createCheckoutSession

Create a Stripe customer when needed, save its external billing ID, and return a hosted subscription Checkout session. Existing Stripe customer contact data and linking metadata are updated. These remote and database writes are not one transaction.

The optional subscription key links the resulting webhook to an existing Subscrio subscription; this call does not create or modify a Stripe subscription directly.

createCheckoutSession(params: { customerKey: string; billingCycleKey: string; subscriptionKey?: string; // Optional: existing subscription key to update stripeSecretKey?: string; // Optional: override config Stripe key successUrl: string; cancelUrl: string; // Convenience options quantity?: number; customerEmail?: string; customerName?: string; allowPromotionCodes?: boolean; billingAddressCollection?: 'auto' | 'required'; paymentMethodTypes?: Stripe.Checkout.SessionCreateParams.PaymentMethodType[]; trialPeriodDays?: number; metadata?: Record<string, string>; // Additional custom metadata // Full Stripe API access stripeOptions?: Partial<Stripe.Checkout.SessionCreateParams>; }): Promise<{ url: string; sessionId: string; }>

Parameters

  • params: Checkout options, including customer, billing cycle, and redirect URLs.

Returns { url: string; sessionId: string }: Checkout result used to redirect the customer.

Example

// acme exists; pro-monthly has a Stripe price ID.
const checkout = await subscrio.stripe.createCheckoutSession({
  customerKey: 'acme', billingCycleKey: 'pro-monthly',
  successUrl: 'https://app.example.com/billing/success',
  cancelUrl: 'https://app.example.com/billing'
});
console.log(checkout.url);
Errors (5)
  • ConfigurationError: No Stripe secret key is available.
  • NotFoundError: The customer, cycle, or supplied subscription is missing.
  • ConflictError: The supplied subscription belongs to another customer.
  • ValidationError: The cycle has no price ID or Stripe returns no Checkout URL.
  • Stripe.errors.StripeError: The Stripe request fails.
Task<(string Url, string SessionId)> CreateCheckoutSessionAsync(string customerKey, string billingCycleKey, string successUrl, string cancelUrl, string? subscriptionKey, string? stripeSecretKey, int? quantity, string? customerEmail, string? customerName, bool? allowPromotionCodes, string? billingAddressCollection, string[]? paymentMethodTypes, int? trialPeriodDays, Dictionary<string, string>? metadata)

Parameters

  • customerKey: Existing Subscrio customer.
  • billingCycleKey: Cycle mapped to a Stripe price.
  • successUrl, cancelUrl: Redirect destinations after Checkout.
  • subscriptionKey: Optional existing subscription to link; must belong to the customer. Defaults to null.
  • stripeSecretKey: Optional secret-key override; defaults to the configured key.
  • quantity: Optional purchase quantity; defaults to 1.
  • customerEmail, customerName: Optional Stripe customer contact values; default null.
  • allowPromotionCodes: Optional promotion-code setting; defaults to the Stripe API behavior.
  • billingAddressCollection: Optional auto or required; defaults to Stripe behavior.
  • paymentMethodTypes: Optional payment-method names; defaults to Stripe behavior.
  • trialPeriodDays: Optional trial duration; default null.
  • metadata: Optional string metadata copied to the session and subscription; default null. Preserve the Subscrio linking keys.

Returns (string Url, string SessionId): Checkout result used to redirect the customer.

Example

// acme exists; pro-monthly has a Stripe price ID.
var checkout = await subscrio.Stripe.CreateCheckoutSessionAsync(
    "acme", "pro-monthly",
    "https://app.example.com/billing/success",
    "https://app.example.com/billing");
Console.WriteLine(checkout.Url);
Errors (5)
  • ConfigurationException: No Stripe secret key is available.
  • NotFoundException: The customer, cycle, or supplied subscription is missing.
  • ConflictException: The supplied subscription belongs to another customer.
  • ValidationException: The cycle has no price ID or Stripe returns no Checkout URL.
  • StripeException: The Stripe request fails.

constructStripeEvent

Verify a webhook signature against the original raw request body. Parsing or reserializing the body before verification changes the signed bytes.

constructStripeEvent(payload: string | Buffer, signatureHeader: string): Stripe.Event

Parameters

  • payload: Original raw webhook body.
  • signatureHeader: Value of the Stripe-Signature header.

Returns Stripe.Event: Verified parsed provider event.

Example

function verifyWebhook(rawBody: string, signature: string) {
  return subscrio.stripe.constructStripeEvent(rawBody, signature);
}
Errors (2)
  • ConfigurationError: The configured webhook secret is missing.
  • Stripe.errors.StripeSignatureVerificationError: Signature verification fails. Invalid JSON can also raise a parsing error.

Subscrio has no .NET equivalent. Use the Stripe SDK's EventUtility.ConstructEvent with the raw body, signature header, and your endpoint secret before calling ProcessStripeEventAsync.

Example

Stripe.Event VerifyWebhook(string rawBody, string signature, string endpointSecret)
{
    return Stripe.EventUtility.ConstructEvent(rawBody, signature, endpointSecret);
}

processStripeEvent

Apply an already-verified provider event to Subscrio. This method does not verify signatures or deduplicate event IDs. Unknown event types are ignored, but still trigger the Stripe before/after hooks. Supported events and their effects are listed under StripeEvent.

Customers are matched by external billing ID, then linking metadata. Subscriptions are matched by Stripe subscription ID, then a customer-owned Subscrio subscription key. Otherwise a new Subscrio subscription is created. Price mapping uses the subscription's first item to find its billing cycle.

processStripeEvent(event: Stripe.Event): Promise<void>

Parameters

Returns No returned value.

Example

async function handleWebhook(rawBody: string, signature: string) {
  const event = subscrio.stripe.constructStripeEvent(rawBody, signature);
  await subscrio.stripe.processStripeEvent(event);
}
Errors (3)
  • NotFoundError: Customer metadata cannot resolve an existing customer, or price/plan mapping is missing.
  • ValidationError: The event has no subscription price or an unsupported subscription status.
  • ConflictError: Customer metadata attempts to replace a different external billing ID.
Task ProcessStripeEventAsync(Stripe.Event stripeEvent)

Parameters

Returns No returned value.

Example

async Task HandleWebhook(string rawBody, string signature, string endpointSecret)
{
    var stripeEvent = Stripe.EventUtility.ConstructEvent(rawBody, signature, endpointSecret);
    await subscrio.Stripe.ProcessStripeEventAsync(stripeEvent);
}
Errors (2)
  • NotFoundException: The customer, price mapping, plan, or required update record is missing.
  • ValidationException: Required subscription data or a supported status is missing.

createStripeSubscription

Deprecated and unsupported: this method always throws. Use Checkout to start a purchase or process a verified webhook to synchronize a subscription.

createStripeSubscription(_customerKey: string, _planKey: string, _billingCycleKey: string, _stripePriceId: string): Promise<Subscription>

Parameters

  • _customerKey, _planKey, _billingCycleKey, _stripePriceId: Unused compatibility parameters.

Returns No value is returned; the method always throws.

Example

// Use the supported Checkout method instead.
const checkout = await subscrio.stripe.createCheckoutSession({
  customerKey: 'acme', billingCycleKey: 'pro-monthly',
  successUrl: 'https://app.example.com/billing/success',
  cancelUrl: 'https://app.example.com/billing'
});
console.log(checkout.url);
Errors (1)
  • ValidationError: Always thrown because direct creation is unsupported.
Task<Subscrio.Core.Domain.Entities.Subscription> CreateStripeSubscriptionAsync(string customerKey, string planKey, string billingCycleKey, string stripePriceId)

Parameters

  • customerKey, planKey, billingCycleKey, stripePriceId: Unused compatibility parameters.

Returns No value is returned; the method always throws.

Example

// Use the supported Checkout method instead.
var checkout = await subscrio.Stripe.CreateCheckoutSessionAsync(
    "acme", "pro-monthly", "https://app.example.com/billing/success",
    "https://app.example.com/billing");
Console.WriteLine(checkout.Url);
Errors (1)
  • NotSupportedException: Always thrown because direct creation is unsupported.

Data types

CheckoutOptions

TypeScript accepts this inline object. .NET accepts the corresponding individual arguments and has no arbitrary Stripe-options parameter.

Field Type Required Default Meaning
customerKey string Yes None Existing Subscrio customer key.
billingCycleKey string Yes None Billing cycle with an external Stripe price ID.
subscriptionKey string No None Existing customer-owned subscription to link.
stripeSecretKey string No Configured key Secret key override.
successUrl string Yes None Successful Checkout redirect.
cancelUrl string Yes None Cancelled Checkout redirect.
quantity number No 1 Stripe subscription item quantity; does not attach Subscrio add-ons.
customerEmail string No None Email sent when creating/updating the Stripe customer.
customerName string No None Name sent when creating/updating the Stripe customer.
allowPromotionCodes boolean No Stripe default Whether Checkout accepts promotion codes.
billingAddressCollection "auto" | "required" No Stripe default Checkout address requirement.
paymentMethodTypes Stripe.Checkout.SessionCreateParams.PaymentMethodType[] No Stripe default Allowed provider payment methods.
trialPeriodDays number No None Provider trial length.
metadata Record<string, string> No None Copied to session and subscription. Values can override generated linking keys; retain their correct values.
stripeOptions Partial<Stripe.Checkout.SessionCreateParams> No None TypeScript-only provider options, merged last. Can replace generated metadata, line items, mode, or customer fields.

See CreateCheckoutSessionAsync for its complete argument list.

CheckoutResult

Hosted Checkout destination, returned as an inline object in TypeScript and a named tuple in .NET.

Field Type Required Default Meaning
url string Yes Not applicable Hosted Checkout URL.
sessionId string Yes Not applicable Stripe Checkout session identifier.
Property Type Required Default Meaning
Url string Yes Not applicable Hosted Checkout URL.
SessionId string Yes Not applicable Stripe Checkout session identifier.

StripeEvent

Stripe.Event is supplied by the installed Stripe SDK, not a Subscrio DTO. It includes the event ID, event type, creation timestamp, and provider object under data.object / Data.Object. The object shape depends on the event type. Subscrio handles these events:

Value Meaning
customer.created / customer.updated Resolve an existing Subscrio customer and link its Stripe customer ID. Does not import a new customer or copy its name/email.
customer.deleted Clear the customer's external billing ID; retain the Subscrio customer.
customer.subscription.created / customer.subscription.updated Create or update the linked subscription, mapped plan/cycle, period dates, trial, cancellation data, and metadata.
customer.subscription.deleted Set the linked subscription's expiration time; retain the record. Missing subscriptions are ignored.
invoice.payment_succeeded Update matching subscription period dates from the matching price line, or the first line as fallback. Missing links are ignored.

Renewal processing does not clear temporary overrides. Call the explicit temporary-override clearing method when your workflow needs that effect. Stripe schedule IDs are stored in subscription metadata as stripeScheduleId.