KDPika Licensing Sign inStart free
API v1
Show all languages
Browse documentation

Choose a page in the navigation drawer.

KDPika Licensing · API v1 Advanced

Sell with Stripe

Verified Stripe purchase-to-license reference with native proof, durable mapping and honest lifecycle boundaries.

On this page
Updated 2026-10-18 UTCDownload Markdown

Connect your own Stripe store to KDPika licensing through a verified, durable backend. This does not add a processor to KDPika platform subscriptions.

What you will learn

  • Configure native notifications and approved product/plan mappings.
  • Issue once after confirmed payment, then handle supported lifecycle changes.
  • Deliver a saved key privately and test without exposing buyer/card data.

Prerequisites

  • Complete the Sandbox quickstart and store service setup.
  • Use your own provider merchant account and private backend credentials; never KDPika's platform billing credentials.
  • Have a product-scoped Sandbox management key with licenses:read and licenses:write.
  • Configure one eligible quantity-one line. Mixed baskets, multi-seat quantities and partial refunds need an explicitly reviewed policy.

Configure the provider

  1. Create your own Stripe Test-mode product and Price. Use a single eligible Price and quantity one in Checkout or a Payment Link.
  2. For one-time sales use Checkout payment mode. For subscriptions use subscription mode. A Payment Link ultimately creates a Checkout Session and uses the same verification below.
  3. In Workbench create a Snapshot webhook destination for Your account, not Connect accounts. Pin its API version to 2025-07-30.basil, matching this source and Stripe-Version header.
  4. Subscribe to the events in the table below; set the destination to your own HTTPS /provider-event endpoint. Save that destination's signing secret privately.
  5. Set KDP_STORE_API_KEY to your private sk_test_ key, KDP_STORE_WEBHOOK_SECRET to the endpoint secret, seller_id to the acct_ ID returned by GET /v1/account, and api_version to 2025-07-30.basil.
  6. Map each verified price_ ID in offer_map. Do not use a display name or a browser-selected plan as a mapping key.

Verify before granting access

Stripe-Signature authenticates the exact timestamp, one period and raw body with HMAC-SHA256. The reference accepts multiple v1 signatures, checks a 300-second timestamp window and fetches the event again with your private key. GET /v1/account must match seller_id; Connect events are refused. Event and payment objects must match the configured mode.

Provider verification, receipt and fulfillment are separate. HTTP 202 only means the authenticated notification was saved. A buyer redirect or successful browser message never creates a license. Only the backend worker can authorize the scoped licensing write after current provider reads.

Event and lifecycle mapping

NotificationConfirmed evidenceLicensing decision
checkout.session.completed / checkout.session.async_payment_succeededCurrent payment-mode Session complete, payment_status paid, one mapped line and current successful PaymentIntent/chargeIssue once; the Session ID is the create Idempotency-Key. Subscription-mode Sessions are skipped.
invoice.paidCurrent paid invoice with no remaining amount, active subscription, matching single price, initial or cycle billing reasonInitial subscription: issue with the Stripe event ID as create Idempotency-Key. Later invoice: renew once by invoice ID; restore first if suspended.
invoice.payment_failedCurrent subscription is past_due or unpaidSuspend. An old failure received after recovery does not suspend an active subscription.
customer.subscription.updated / customer.subscription.deletedCurrent cancellation intent or canceled stateRecord cancellation; preserve already-paid license time.
charge.refundedCurrent charge fully refundedRevoke the mapped license. Partial refunds require review.
charge.dispute.created / charge.dispute.updated / charge.dispute.closedCurrent dispute and its chargeSuspend while disputed/lost; restore on won only if not refunded. Terminal revocation cannot be undone.

Basil invoices use parent.subscription_details.subscription and line.pricing.price_details.price. Invoice payment references are read from /v1/invoice_payments; old invoice.subscription/payment_intent examples are not substituted. A Checkout success page never authorizes issuance. Delayed payments wait for confirmed paid state. Do not grant twice from checkout and invoice events.

Proration/manual invoices, multiple lines and in-place plan changes are held, not guessed. Paid-out-of-band invoices can be paid without a card charge: decide whether you authorize that Stripe administrative payment state in your own operations. This sample follows authoritative invoice paid state, not a promise of bank settlement or an exact provider-period-end setter.

Server examples and deployment

The PHP application contains the native verification, provider API reads, durable ledger and licensing worker. Optional Node/Python examples are complete raw-body ingress servers with an explicit PHP service dependency, not independent native payment workers. The PHP shared-hosting path needs neither Node nor a long-running process.

  1. Download all exact sources and check the SHA-256 manifest.
  2. Follow the shared setup without changing the provider/module source or putting private config under a web root.
  3. Set config.json provider/merchant/mode and offer_map; set fulfillment.json source to the identical provider string and map the approved internal offer to your product plan.
  4. Run the private work cron, inspect its aggregate states, and then run the separate mail cron. Keep both ledgers/backups persistent.
  5. Configure SMTP delivery for your own sender. It reuses the encrypted saved key; it never creates another license to resend.

Complete provider module

This exact module is loaded by the shared normalizer. It depends on the complete native authentication and HTTP client and durable service source. It is not a standalone copy/paste webhook endpoint.

stripe.phpphp
<?php
declare(strict_types=1);
// Complete provider module for StoreNormalizer; loaded by normalize.php.
// Requires the shared service/archive, not a standalone payment endpoint.
trait StoreStripeNormalizer
{
    private function stripe(array $event): array
    {
        $account = $this->get('/v1/account');
        storeRequire(($account['id'] ?? null) === $this->config['seller_id'] && empty($event['account']), 'WRONG_MERCHANT_OR_CONNECT_EVENT');
        $verified = $this->get('/v1/events/' . $this->ref($event['id'] ?? null));
        storeRequire(($verified['id'] ?? null) === $event['id'] && ($verified['type'] ?? null) === ($event['type'] ?? null), 'EVENT_NOT_CONFIRMED');
        $this->mode($verified['livemode'] ?? null);
        $type = $verified['type']; $object = $verified['data']['object'] ?? [];
        $id = $object['id'] ?? null;
        if (in_array($type, ['checkout.session.completed', 'checkout.session.async_payment_succeeded'], true)) {
            $session = $this->get('/v1/checkout/sessions/' . $this->ref($id));
            $this->mode($session['livemode'] ?? null);
            if (($session['mode'] ?? '') === 'subscription') { return []; } // Invoice is the sole subscription payment authority.
            storeRequire(($session['mode'] ?? null) === 'payment' && ($session['status'] ?? null) === 'complete', 'CHECKOUT_NOT_COMPLETE');
            if (($session['payment_status'] ?? '') !== 'paid') { return []; } // Wait for delayed-payment success.
            $lines = $this->get('/v1/checkout/sessions/' . $this->ref($id) . '/line_items?limit=2');
            storeRequire(($lines['has_more'] ?? true) === false, 'MULTI_LINE_ORDER_REQUIRES_REVIEW');
            $line = $this->one($lines['data'] ?? []);
            $pi = $session['payment_intent'] ?? null;
            storeRequire(is_string($pi), 'PAYMENT_INTENT_REQUIRED');
            $intent = $this->get('/v1/payment_intents/' . $this->ref($pi));
            storeRequire(($intent['status'] ?? '') === 'succeeded', 'PAYMENT_NOT_SUCCEEDED');
            $charge = is_string($intent['latest_charge'] ?? null) ? $intent['latest_charge'] : null;
            if ($charge !== null) {
                $current = $this->get('/v1/charges/' . $this->ref($charge));
                storeRequire(($current['paid'] ?? null) === true && ($current['amount_refunded'] ?? 0) === 0 && ($current['disputed'] ?? false) === false, 'PAYMENT_ALREADY_REFUNDED_OR_DISPUTED');
            }
            $buyer = $session['customer_details'] ?? [];
            return [$this->paid((string) $id, (string) $id, (string) ($line['price']['id'] ?? ''),
                (string) ($buyer['email'] ?? ''), (string) ($buyer['name'] ?? ''), false,
                array_values(array_filter([$pi, $charge])), (string) $id)];
        }
        if (in_array($type, ['invoice.paid', 'invoice.payment_failed'], true)) {
            $invoice = $this->get('/v1/invoices/' . $this->ref($id)); $this->mode($invoice['livemode'] ?? null);
            $subId = $invoice['parent']['subscription_details']['subscription'] ?? null;
            storeRequire(is_string($subId), 'SUBSCRIPTION_INVOICE_REQUIRED');
            $subscription = $this->get('/v1/subscriptions/' . $this->ref($subId)); $this->mode($subscription['livemode'] ?? null);
            if ($type === 'invoice.payment_failed') {
                if (!in_array($subscription['status'] ?? '', ['past_due', 'unpaid'], true)) { return []; }
                return [$this->negative($subId, (string) $id . ':failed', 'failed')];
            }
            storeRequire(($invoice['status'] ?? '') === 'paid' && ($invoice['amount_remaining'] ?? -1) === 0 && ($subscription['status'] ?? '') === 'active', 'INVOICE_NOT_CURRENTLY_PAID');
            storeRequire(in_array($invoice['billing_reason'] ?? '', ['subscription_create', 'subscription_cycle'], true), 'PRORATION_OR_MANUAL_INVOICE_REQUIRES_REVIEW');
            storeRequire(($invoice['lines']['has_more'] ?? true) === false, 'PAGINATED_INVOICE_REQUIRES_REVIEW');
            $line = $this->one($invoice['lines']['data'] ?? []);
            $subLine = $this->one($subscription['items']['data'] ?? []);
            $price = $line['pricing']['price_details']['price'] ?? null;
            storeRequire(is_string($price) && $price === ($subLine['price']['id'] ?? null), 'SUBSCRIPTION_PRICE_MISMATCH');
            $links = [$subId, (string) $id];
            $payments = $this->get('/v1/invoice_payments?invoice=' . $this->ref($id) . '&limit=2');
            storeRequire(($payments['has_more'] ?? true) === false, 'PAYMENT_MAPPING_REQUIRES_REVIEW');
            foreach ($payments['data'] ?? [] as $payment) {
                $pi = $payment['payment']['payment_intent'] ?? null;
                if (is_string($pi)) {
                    $intent = $this->get('/v1/payment_intents/' . $this->ref($pi));
                    storeRequire(($intent['status'] ?? '') === 'succeeded', 'PAYMENT_NOT_SUCCEEDED');
                    $links[] = $pi;
                    if (is_string($intent['latest_charge'] ?? null)) {
                        $charge = $this->get('/v1/charges/' . $this->ref($intent['latest_charge']));
                        storeRequire(($charge['paid'] ?? null) === true && ($charge['amount_refunded'] ?? 0) === 0 && ($charge['disputed'] ?? false) === false, 'PAYMENT_ALREADY_REFUNDED_OR_DISPUTED');
                        $links[] = $intent['latest_charge'];
                    }
                }
            }
            return [$this->paid($subId, (string) $id, $price, (string) ($invoice['customer_email'] ?? ''),
                (string) ($invoice['customer_name'] ?? ''), true, $links, (string) $event['id'], $invoice['billing_reason'] === 'subscription_create')];
        }
        if ($type === 'customer.subscription.deleted' || $type === 'customer.subscription.updated') {
            $subscription = $this->get('/v1/subscriptions/' . $this->ref($id));
            $this->mode($subscription['livemode'] ?? null);
            if (($subscription['cancel_at_period_end'] ?? false) || ($subscription['status'] ?? '') === 'canceled') {
                return [$this->negative((string) $id, (string) $event['id'], 'cancelled')];
            }
            return [];
        }
        if ($type === 'charge.refunded') {
            $charge = $this->get('/v1/charges/' . $this->ref($id)); $this->mode($charge['livemode'] ?? null);
            storeRequire(($charge['refunded'] ?? false) && ($charge['amount_refunded'] ?? -1) === ($charge['amount'] ?? -2), 'PARTIAL_REFUND_REQUIRES_REVIEW');
            return [$this->negative((string) ($charge['payment_intent'] ?? ''), (string) $event['id'], 'refunded')];
        }
        if (str_starts_with($type, 'charge.dispute.')) {
            $dispute = $this->get('/v1/disputes/' . $this->ref($id)); $this->mode($dispute['livemode'] ?? null);
            $chargeId = $dispute['charge'] ?? null; $charge = $this->get('/v1/charges/' . $this->ref($chargeId));
            $state = ($dispute['status'] ?? '') === 'won' ? 'recovered' : 'disputed';
            storeRequire(($charge['amount_refunded'] ?? 0) === 0 || $state !== 'recovered', 'REFUNDED_DISPUTE_REQUIRES_REVIEW');
            return [$this->negative((string) $chargeId, (string) $event['id'], $state)];
        }
        return [];
    }
}

Test in Sandbox

  1. Confirm invalid/missing proof cannot issue, and no key or API credential appears in the HTTP reply.
  2. Complete one permitted Test purchase in your merchant account. Confirm the provider delivery, then run work and verify one DONE issue and a saved encrypted key.
  3. Deliver to your verified test inbox and activate that key with the same buyer email and Sandbox App ID. Test a mismatched email too.
  4. Redeliver the same event and overlapping supported paid events. Confirm no second key and no additional renewal days for the same paid receipt.
  5. For supported subscriptions, test initial payment, another confirmed paid period, current failure/recovery and cancellation. Verify cancellation does not remove already-paid time.
  6. Test a supported full refund and any exposed dispute lifecycle. Check revoked/suspended state in KDPika; never simulate a refund only by editing the browser return URL.
  7. Test stale events and a missing initial mapping. Unknown, partial or unsupported cases must be held for review, not silently fulfilled.

Expected result: one authorized initial license, one additive extension per supported new paid receipt, no duplicate grant, no access from an unverified event, and a private delivery record. Renewal adds your mapped integer days, not an exact calendar-period-end update.

Verification boundary

The exact source was executed through local HTTP ingress and explicit synthetic provider-schema API fixtures, with real isolated KDPika Sandbox issuance, activation and supported lifecycle writes. Fixture signatures use local test secrets, not a provider's private signing infrastructure. No real Stripe account purchase is claimed. Your account's permissions, actual delivery format, TLS, provider checkout and email inbox still need the procedure above before Live use. Native WordPress/merchant account execution was unavailable in this documentation environment; this is the explicit contract-test boundary, not recorded-payment evidence.

Go-live checklist

  • Review the unsupported boundaries above; do not sell a lifecycle this adapter does not implement.
  • Complete your provider account verification and real Test delivery procedure; check merchant, recipient, item and mode.
  • Use a separate Live config/state and scoped Live KDPika key; set KDP_CONFIRM_LIVE only after review. Never turn existing Sandbox ledgers into Live by editing their binding.
  • Replace provider credentials/destination secret with the matching Live account values. Do not reuse example placeholders.
  • Remove every loopback test override, use verified HTTPS and keep credentials and SQLite/encryption backups outside all web roots.
  • Monitor private REVIEW/IN_FLIGHT and mail failures. A missing acknowledgement is not proof a write or email did not happen; reconcile before retrying.
  • Retain business-effect identities to prevent reissuance. Apply your documented retention, refund, support and key-redelivery policies.

Common mistakes

  • Shipping a server management key inside an application or theme.
  • Issuing from a redirect, subscription-created event or unverified notification.
  • Granting both initial checkout and initial recurring invoice independently.
  • Deleting the durable ledger or creating a new effect ID after a timeout.
  • Treating a saved key or SMTP acceptance as confirmed inbox delivery.

Official sources

Reviewed for this reference on 18 October 2026. Provider documentation can change independently; check your pinned API and account before upgrading.

Expected result

Only a confirmed provider purchase authorizes a licensing effect. A durable HTTP receipt, completed licensing operation and SMTP acceptance are separate outcomes. Inspect aggregate worker states and verify the resulting license with the same buyer email; no full key appears in public replies.

Security notes

Use least-privilege private provider and product-scoped licensing credentials, verified HTTPS, owner-only persistent state and separate secrets per account/environment. Never trust browser payment claims. Preserve held operations after an unknown result and reconcile before another write; exactly-once behavior across systems is not guaranteed.

Troubleshooting

For a receipt refusal check raw-byte preservation, the matching endpoint secret/account/mode, server clock where applicable and the private bootstrap layout. For REVIEW/IN_FLIGHT inspect provider state, safe private error codes and the licensing ledger before retrying. Missing permissions, recipient data or an initial mapping are not successful payments. For mail verify the separate SMTP ledger and provider delivery evidence. Do not post raw events, keys or SQLite files publicly.

Next steps

Run the selected provider Sandbox procedure, then test private key email delivery. Review supported recipe limitations before enabling Live.

Was this page helpful?

Choose an answer

Do not include personal data, license keys or credentials. Retained for up to 30 days. This is not a support inbox.

Search documentation

Arrow keys to move, Enter to open, Escape to close. Search stays in your browser.

Cookie settings