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 Lemon Squeezy

Verified Lemon Squeezy 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 Lemon Squeezy 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 a Test-mode store product and variant. Decide whether it is one-time or subscription; save the variant and store IDs.
  2. Create a signed webhook for your own HTTPS /provider-event endpoint. Select order_created, order_refunded, subscription_payment_success, subscription_payment_failed, subscription_payment_recovered, subscription_payment_refunded, subscription_cancelled, subscription_updated and subscription_expired.
  3. Set KDP_STORE_WEBHOOK_SECRET to your chosen webhook secret and KDP_STORE_API_KEY to your private API key.
  4. Set provider/source to lemon-squeezy, environment to sandbox and seller_id to the numeric store ID as a JSON string.
  5. Map variant IDs as strings in offer_map. The reference uses JSON:API headers, verifies store_id and test_mode and reads current order/subscription/invoice records.

Verify before granting access

X-Signature is the hexadecimal HMAC-SHA256 of raw request bytes. It does not provide a timestamp; durable business-effect deduplication is essential. meta.event_name identifies the notification type but does not replace authenticated current API reads.

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
order_createdCurrent paid one-time order; authenticated order-items query confirms exactly one quantity-one line; variant is not a subscriptionIssue once by order ID. Subscription orders are skipped so the invoice is the sole initial payment authority.
subscription_payment_success / subscription_payment_recoveredCurrent paid, nonrefunded invoice; active subscription; billing_reason initial or renewalIssue initial invoice; renew an existing subscription once per invoice. Recovering a suspended license restores, then renews once.
subscription_payment_failed / subscription_updatedCurrent subscription state is past_dueSuspend; stale failure after current recovery does not remove active access.
subscription_cancelled / subscription_expiredCurrent cancellation/expiry stateCancel intent preserves paid access; expired suspends.
order_refunded / subscription_payment_refundedCurrent order/invoice confirms a full refundRevoke mapped access. Partial refunds stop for review.

The first_order_item field alone does not prove a single-item purchase: the reference additionally queries order-items filtered by the authenticated order ID. Subscription invoice billing_reason updated is not treated as a normal new paid period. Lemon Squeezy native license keys are a different system; these examples create KDPika licenses only. A generic dispute webhook is not invented: reconcile chargeback outcomes through supported merchant records and your reviewed policy.

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.

lemon.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 StoreLemonNormalizer
{
    private function lemon(array $event): array
    {
        $type = $event['meta']['event_name'] ?? ''; $native = $event['data'] ?? [];
        $resource = $native['type'] ?? '';
        storeRequire(in_array($resource, ['orders', 'subscriptions', 'subscription-invoices'], true), 'UNSUPPORTED_RESOURCE');
        $current = $this->get('/v1/' . $resource . '/' . $this->ref($native['id'] ?? null))['data'] ?? [];
        $attributes = $current['attributes'] ?? [];
        $this->mode(isset($attributes['test_mode']) ? !$attributes['test_mode'] : null);
        if ($resource === 'orders') {
            storeRequire((string) ($attributes['store_id'] ?? '') === (string) $this->config['seller_id'], 'WRONG_STORE');
            if ($type === 'order_refunded') {
                storeRequire(($attributes['refunded'] ?? false) && ($attributes['refunded_amount'] ?? -1) === ($attributes['total'] ?? -2), 'PARTIAL_REFUND_REQUIRES_REVIEW');
                return [$this->negative((string) $current['id'], hash('sha256', json_encode($current, JSON_THROW_ON_ERROR)), 'refunded')];
            }
            if ($type !== 'order_created') { return []; }
            storeRequire(($attributes['status'] ?? '') === 'paid', 'ORDER_NOT_PAID');
            $items = $this->get('/v1/order-items?filter%5Border_id%5D=' . $this->ref($current['id']) . '&page%5Bsize%5D=2');
            storeRequire(($items['meta']['page']['total'] ?? -1) === 1, 'MULTI_LINE_ORDER_REQUIRES_REVIEW');
            $item = $this->one($items['data'] ?? []);
            $line = $item['attributes'] ?? [];
            storeRequire((string) ($line['order_id'] ?? '') === (string) $current['id'] && (int) ($line['quantity'] ?? 0) === 1, 'SINGLE_UNIT_LINE_REQUIRED');
            $variant = $this->get('/v1/variants/' . $this->ref($line['variant_id'] ?? null))['data']['attributes'] ?? [];
            storeRequire(is_bool($variant['is_subscription'] ?? null), 'VARIANT_KIND_NOT_CONFIRMED');
            if (($variant['is_subscription'] ?? false) === true) { return []; }
            return [$this->paid((string) $current['id'], (string) $current['id'], (string) ($line['variant_id'] ?? ''),
                (string) ($attributes['user_email'] ?? ''), (string) ($attributes['user_name'] ?? ''), false)];
        }
        $subscription = $resource === 'subscriptions' ? $current : ($this->get('/v1/subscriptions/' . $this->ref($attributes['subscription_id'] ?? null))['data'] ?? []);
        $sub = $subscription['attributes'] ?? [];
        storeRequire((string) ($sub['store_id'] ?? '') === (string) $this->config['seller_id'], 'WRONG_STORE');
        $this->mode(isset($sub['test_mode']) ? !$sub['test_mode'] : null);
        $order = (string) ($subscription['id'] ?? '');
        if (in_array($type, ['subscription_payment_success', 'subscription_payment_recovered'], true)) {
            storeRequire(($attributes['status'] ?? '') === 'paid' && ($attributes['refunded'] ?? false) === false && ($attributes['refunded_amount'] ?? 0) === 0 && ($sub['status'] ?? '') === 'active', 'SUBSCRIPTION_NOT_PAID');
            storeRequire(in_array($attributes['billing_reason'] ?? '', ['initial', 'renewal'], true), 'PRORATION_REQUIRES_REVIEW');
            return [$this->paid($order, (string) $current['id'], (string) ($sub['variant_id'] ?? ''),
                (string) ($sub['user_email'] ?? ''), (string) ($sub['user_name'] ?? ''), true,
                [(string) ($sub['order_id'] ?? ''), (string) $current['id']], null, $attributes['billing_reason'] === 'initial')];
        }
        $state = match (true) {
            $type === 'subscription_payment_refunded' => 'refunded',
            ($sub['status'] ?? '') === 'past_due' => 'failed',
            ($sub['cancelled'] ?? false) === true || ($sub['status'] ?? '') === 'cancelled' => 'cancelled',
            ($sub['status'] ?? '') === 'expired' => 'ended', default => null
        };
        if ($state === 'refunded') {
            storeRequire(($attributes['refunded'] ?? false) && ($attributes['refunded_amount'] ?? -1) === ($attributes['total'] ?? -2), 'PARTIAL_REFUND_REQUIRES_REVIEW');
        }
        return $state === null ? [] : [$this->negative($order, hash('sha256', json_encode($current, JSON_THROW_ON_ERROR)), $state)];
    }
}

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 Lemon Squeezy 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