PHP code example of sparkcrm / spark-sdk

1. Go to this page and download the library: Download sparkcrm/spark-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sparkcrm / spark-sdk example snippets




use SparkCheckout\SparkCheckout;

$spark = new SparkCheckout($apiToken);



use SparkCheckout\SparkCheckout;
use SparkCheckout\Exception\SparkException;

$apiToken = getenv('SPARK_CHECKOUT_TOKEN'); // your SparkCRM DTC API token

// ── Request 1: initial landing-page load ──────────────────────────────────
session_start();                        // default store lives in $_SESSION
$spark = new SparkCheckout($apiToken);

// Opens a checkout session AND captures ip, user_agent, utm_*, affiliate,
// sub1-5 and any other query params, then stores session_id + context so every
// later call reuses it automatically.
$spark->init(['campaign' => 1042]);     // integer campaign id ( session + context

    $result = $spark->createOrder([
        'payment' => ['method' => 'card', 'card_number' => '...', 'card_exp' => '12/26', 'card_cvv' => '123'],
        'billing' => ['address' => '...', 'zip' => '90001', 'country' => 'US'],
    ]); // a lead exists -> charges the existing order (/orders/payment)

    // Branch in this order — declines, redirects and duplicates are RESULTS, not exceptions:
    if ($result->needsRedirect()) {
        header('Location: '.$result->redirectUrl());  // PayPal etc.
        exit;
    } elseif ($result->isDeclined()) {
        echo 'Declined: '.$result->declineCode();
    } elseif ($result->isApproved()) {
        $spark->processUpsell(['upsell_id' => 'UP-1', 'quantity' => 1]); // optional
        $spark->completeOrder();          // fires autoresponders/webhooks, then clears state
        echo 'Approved! Order '.$result->orderNumber();
    }
} catch (SparkException $exception) {     // 401/403/404/422-field/429/402/5xx (see Errors)
    echo 'Checkout error ('.$exception->httpStatus().'): '.$exception->getMessage();
}

$spark = new SparkCheckout($apiToken, request: $psrServerRequest);
$spark->init(['campaign' => 1042]);

use SparkCheckout\Config;

// Hardened: only trust these proxies' forwarded headers.
$config = new Config($apiToken, trustedProxies: ['10.0.0.0/8', '192.168.1.5']);

// Strict: ignore forwarded headers entirely, use REMOTE_ADDR only.
$config = new Config($apiToken, trustedProxies: []);

// Override the header priority (defaults shown) — e.g. put CF-Connecting-IP first behind Cloudflare:
$config = new Config($apiToken, trustedProxyHeaders: ['X-Forwarded-For', 'X-Real-IP', 'CF-Connecting-IP']);

$spark = new SparkCheckout($apiToken, config: $config, request: $psrServerRequest);

$spark->init([
    'campaign'   => 1042,
    'ip_address' => $buyerIp,
    'user_agent' => $buyerUserAgent,
    'affiliate'  => 'AFF-123',
]);

use SparkCheckout\SparkCheckout;
use SparkCheckout\Store\CacheStore;

$store = new CacheStore($psr16Cache, $correlationToken);
$spark = new SparkCheckout($apiToken, $store);

use SparkCheckout\Store\SessionStore;

$spark = new SparkCheckout($apiToken, new SessionStore(secure: false));
// or leave the host's session config untouched: new SessionStore(configureCookie: false)

$result = $spark->createOrder([...]);

$result->isApproved();        // 2xx + success, not declined/redirect (incl. "processing")
$result->isDeclined();        // gateway decline or pre-gateway decline
$result->declineCode();       // e.g. "05"
$result->isDuplicate();       // full-order dedupe; ->orderNumber() is the existing order
$result->needsRedirect();     // PayPal
$result->redirectUrl();
$result->orderNumber();
$result->transactionNumber();
$result->message();
$result->raw();               // the untouched response body

// Retry a declined MAIN charge (order_number auto-injected).
// Omit 'payment' to retry the existing method, or pass a fresh card.
if ($result->isDeclined()) {
    $result = $spark->reprocessPayment([
        'payment' => ['method' => 'card', 'card_number' => '...', 'card_cvv' => '...'],
        // optional: 'amount', 'gateway_id', 'affiliate', 'sub1'..'sub5'
    ]);
}

// Retry one declined upsell transaction.
$upsell = $spark->processUpsell(['upsell_id' => 'UP-1', 'quantity' => 1]);
if ($upsell->isDeclined()) {
    $retry = $spark->reprocessUpsell($upsell->transactionNumber());
    if ($retry->inProgress()) {
        // another reprocess for this transaction is already running (409)
    }
}

// Phase 1 — create the order. return_url + cancel_url are and this no-prior-lead paypal_wallet path) email' => $email, 'first_name' => $first, 'last_name' => $last],
    'products' => [['offer_id' => 'OFF-1', 'quantity' => 1]],
    'payment' => [
        'method'     => 'paypal_wallet',
        'return_url' => 'https://shop.test/checkout/return',
        'cancel_url' => 'https://shop.test/checkout/cancel',
        // optional: 'external_payment_id' => 1234,
    ],
]);

if ($result->needsRedirect()) {
    header('Location: '.$result->redirectUrl());
    exit;
}

// Phase 2 — the customer returns to return_url (a new request).
// The persistent store (cookie/cache) survived the redirect.
$spark->resume();                 // or: $spark->resume($_GET['spark_order'] ?? null);
$capture = $spark->capture();     // POST /checkout/orders/capture (idempotent)

$capture->isApproved();
$capture->payerEmail();
$capture->subscriptionCreated();
$capture->subscriptionNumber();

// On your cancel_url page:
if ($spark->wasCanceled()) {
    $spark->abandon(); // clears the stored funnel state so the next order starts clean
}

// Tax quote (explicit; createOrder never auto-calls it).
$tax = $spark->calculateTax([
    'to_address' => ['country' => 'US', 'state' => 'CA', 'zip' => '90001'],
    'line_items' => [['quantity' => 1, 'unit_price' => 49.00]],
]);
$tax->enabled(); // false when the campaign has no tax provider (zeros, not an error)

// Subscription status — by the current order, or an explicit customer number.
$subscription = $spark->checkSubscription();          // uses the stored order
$spark->checkSubscription('CUST-123456-78901');       // explicit
$subscription->isActive();
$subscription->subscriptionNumbers();

// Refund a transaction. Omit `amount` for a full refund; pass isExternal: true
// to record an external (admin-recorded, off-gateway) refund.
$spark->refund('TXN-123456-789012', amount: 9.99, reason: 'customer request');
$spark->refund('TXN-123456-789012');                       // full refund
$spark->searchTransactions(['order_number' => 'ORD-1']);   // transaction search

// Search helpers (paginated).
$orders = $spark->searchOrders(['customer_email' => '[email protected]']);
$orders->items();
$orders->pagination(); // total / per_page / current_page / last_page

use SparkCheckout\Config;
use SparkCheckout\Normalization\AliasMap;

$config = new Config($apiToken, aliasMap: new AliasMap(['affiliate' => ['my_aff']]));
$spark = new SparkCheckout($apiToken, config: $config);

use SparkCheckout\Config;
use SparkCheckout\Testing\TestCard;

$spark = new SparkCheckout($apiToken, config: new Config($apiToken, testMode: true));
$spark->isTestMode(); // true

// Canonical Luhn-valid test cards + a ready-to-use payment block:
$spark->createOrder(['payment' => TestCard::approved()]);   // sandbox-approved card
$spark->createOrder(['payment' => TestCard::declined()]);   // sandbox-declined card
$spark->createOrder(['payment' => TestCard::payment(TestCard::AMEX)]);

use SparkCheckout\Laravel\SparkCheckoutFacade as Spark;
use SparkCheckout\SparkCheckout;

// Facade
Spark::init(['campaign' => 1042]);

// or resolve directly
app(SparkCheckout::class)->createLead([...]);