Blog

Accept crypto payments in PHP and Laravel

CoinStackUpdated 11 min read
Integrations

To accept crypto payments in PHP, your server sends the order amount to https://coinstack.net/api/v1/checkouts with a Bearer API key, redirects the customer to the url it gets back, and marks the order paid when a signed checkout.completed webhook arrives. In Laravel the same flow uses the Http client, a webhook route excluded from CSRF protection, a signature check on getContent() and a queued job. The Laravel code was tested on Laravel 13.45 with PHP 8.5 in December 2026.

What do you need before writing code?

Four things, all from the dashboard and your server:

  1. A CoinStack account. Instant sign-up with an email code or Google creates the account and the wallet your USDC settles to.
  2. An API key. Under Developers, select New API key, set Access to Read and write, and copy the key. It starts with sk_ and is shown once.
  3. A webhook. Under Developers, select Add webhook and enter an https:// URL on a domain name (not an IP address), such as https://example.com/webhooks/coinstack. The signing secret appears once, starting with whsec_; save it straight away.
  4. A server that CoinStack can reach over HTTPS, with PHP's cURL extension for the plain version.

Put the key and the secret in environment variables (COINSTACK_API_KEY, COINSTACK_WEBHOOK_SECRET), never in code or in the browser. If your PHP application is WHMCS, WooCommerce, Blesta or PrestaShop, skip this tutorial: the WHMCS gateway module and the WooCommerce plugin do all of it, including registering their own webhook.

Plain PHP: create a checkout with cURL

The quickstart shows a single cURL call. Wrapping it in a function lets the same code create checkouts and read them back. Every response has the shape {"success": true, "response": {...}} or {"success": false, "response": "message"}, so the function checks success and returns response.

<?php
// coinstack.php

function coinstack(string $method, string $path, ?array $payload = null): array
{
    $curl = curl_init('https://coinstack.net/api/v1' . $path);
    $headers = ['Authorization: Bearer ' . getenv('COINSTACK_API_KEY')];

    if ($payload !== null) {
        $headers[] = 'Content-Type: application/json';
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload));
    }

    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => $headers,
    ]);

    $raw = curl_exec($curl);

    if ($raw === false) {
        throw new RuntimeException('CoinStack request failed: ' . curl_error($curl));
    }

    $body = json_decode($raw, true);

    if (!is_array($body) || ($body['success'] ?? false) !== true) {
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        throw new RuntimeException('CoinStack: ' . ($body['response'] ?? "HTTP $status"));
    }

    return $body['response'];
}

The is_array check is there because one kind of failure is not JSON: the errors page says a body that is not valid JSON, or is sent without Content-Type: application/json, gets a 4xx with a plain text body.

The page that starts the payment creates the checkout and redirects:

<?php
// pay.php

require __DIR__ . '/coinstack.php';

$order = find_order((int) $_POST['order_id']); // your own lookup

$checkout = coinstack('POST', '/checkouts', [
    'amount' => $order['total'],          // a string such as '49.00'
    'currency' => 'USD',
    'reference' => 'order-' . $order['id'],
    'metadata' => ['order_id' => (string) $order['id']],
    'success_url' => 'https://example.com/orders/' . $order['id'],
    'cancel_url' => 'https://example.com/cart',
])['checkout'];

save_checkout_id($order['id'], $checkout['checkout_id']); // your own update

header('Location: ' . $checkout['url'], true, 303);
exit;

Send amount as a string with no more decimal places than the currency has, and in any of the 146 supported currencies. The checkout must be worth between 1 and 1,000,000 US dollars. Metadata values must be strings, which is why the order ID is cast. Save checkout_id against the order: it is how the webhook finds the order later.

One trap with retries: creating a checkout twice makes 2 checkouts. If the request times out, list checkouts with ?reference=order-1042 before trying again, in case the first one went through.

Plain PHP: confirm the payment with a webhook

The customer may close the checkout page without returning to success_url, so the order is marked paid from the webhook, never from the return visit. This script is the webhooks guide verification code followed by an order update.

<?php
// webhook.php

require __DIR__ . '/coinstack.php';

$secret = getenv('COINSTACK_WEBHOOK_SECRET');
$body = file_get_contents('php://input');
$parts = [];

foreach (explode(',', $_SERVER['HTTP_COINSTACK_SIGNATURE'] ?? '') as $part) {
    $pair = explode('=', $part, 2);

    if (count($pair) === 2) {
        $parts[$pair[0]] = $pair[1];
    }
}

$timestamp = $parts['t'] ?? '';
$expected = hash_hmac('sha256', $timestamp . '.' . $body, $secret);

if (!hash_equals($expected, $parts['v1'] ?? '') || abs(time() - (int) $timestamp) > 300) {
    http_response_code(400);
    exit('Invalid signature');
}

$event = json_decode($body, true);

$pdo = new PDO(getenv('DATABASE_DSN'), getenv('DATABASE_USER'), getenv('DATABASE_PASSWORD'));
$checkoutId = $event['data']['checkout']['checkout_id'] ?? '';
$known = $pdo->prepare('SELECT 1 FROM orders WHERE checkout_id = ?');
$known->execute([$checkoutId]);

if (in_array($event['kind'], ['checkout.completed', 'checkout.resolved'], true) && $known->fetchColumn()) {
    $checkout = coinstack('GET', '/checkouts/' . rawurlencode($checkoutId))['checkout'];

    if (in_array($checkout['status'], ['completed', 'resolved'], true)) {
        $update = $pdo->prepare("UPDATE orders SET status = 'paid' WHERE checkout_id = ? AND status = 'unpaid'");
        $update->execute([$checkoutId]);

        if ($update->rowCount() === 1) {
            // First time this order is marked paid: fulfil it here.
        }
    }
}

http_response_code(200);

Four choices in it are deliberate. php://input is the body exactly as sent, which is what the signature covers. The script ignores checkouts it has no order for, such as the sample in the dashboard's Send test, which has no real checkout behind it. It reads the checkout from the API before trusting it, so an event that arrives late or out of order cannot mislead it. And the UPDATE ... AND status = 'unpaid' only changes a row once, so a duplicate delivery does nothing. resolved counts as paid because it means you accepted an underpayment; underpaid crypto payments explains when that happens.

This version does its work inside the request, which is fine while fulfilment is fast. CoinStack expects a 2xx within 10 seconds. Once fulfilment means provisioning a server or calling other APIs, move it to a queue, which is where Laravel helps.

Laravel: configuration and an API client

Add the credentials to .env and expose them through config/services.php, so the code reads config and works with php artisan config:cache:

// config/services.php
'coinstack' => [
    'key' => env('COINSTACK_API_KEY'),
    'webhook_secret' => env('COINSTACK_WEBHOOK_SECRET'),
],

Laravel's HTTP client replaces the cURL function. post() sends an array as JSON with the right content type, withToken() sets the Bearer header, and a small class keeps the envelope check in one place:

<?php
// app/Services/CoinStack.php

namespace App\Services;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class CoinStack
{
    private function client(): PendingRequest
    {
        return Http::baseUrl('https://coinstack.net/api/v1')
            ->withToken(config('services.coinstack.key'))
            ->acceptJson()
            ->timeout(30);
    }

    public function createCheckout(array $fields): array
    {
        return $this->unwrap($this->client()->post('/checkouts', $fields))['checkout'];
    }

    public function getCheckout(string $checkoutId): array
    {
        return $this->unwrap($this->client()->get('/checkouts/'.rawurlencode($checkoutId)));
    }

    private function unwrap($response): array
    {
        $body = $response->json();

        if (! is_array($body) || ($body['success'] ?? false) !== true) {
            throw new RuntimeException('CoinStack: '.($body['response'] ?? 'HTTP '.$response->status()));
        }

        return $body['response'];
    }
}

getCheckout returns the whole response, which holds checkout, quotes and payments.

Laravel: send the customer to the checkout

An invokable controller creates the checkout for an order and redirects to the hosted page. The example assumes an orders table with total, currency, status (default unpaid) and a nullable unique checkout_id.

<?php
// app/Http/Controllers/OrderPaymentController.php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\CoinStack;

class OrderPaymentController extends Controller
{
    public function __invoke(Order $order, CoinStack $coinstack)
    {
        abort_if($order->status !== 'unpaid', 409);

        $checkout = $coinstack->createCheckout([
            'amount' => number_format((float) $order->total, 2, '.', ''),
            'currency' => $order->currency,
            'reference' => 'order-'.$order->id,
            'metadata' => ['order_id' => (string) $order->id],
            'success_url' => route('orders.show', $order),
            'cancel_url' => route('orders.show', $order),
        ]);

        $order->update(['checkout_id' => $checkout['checkout_id']]);

        return redirect()->away($checkout['url']);
    }
}

number_format turns a decimal column into a string like 49.00; use 0 decimals for a currency such as JPY. redirect()->away() is needed because the checkout page is on another domain. The success_url link appears on the checkout page once it is paid, as a Return to merchant button; it is a convenience for the customer, not a payment signal.

Laravel: the webhook route and CSRF

Routes in routes/web.php run through Laravel's request forgery protection, which rejects a POST without a CSRF token. CoinStack has no token to send, so without an exception every webhook gets 419 and is retried until CoinStack gives up. In testing, the same signed request returned 419 without the exception and 200 with it.

// routes/web.php
use App\Http\Controllers\CoinStackWebhookController;
use App\Http\Controllers\OrderPaymentController;

Route::post('/orders/{order}/pay', OrderPaymentController::class)->name('orders.pay');
Route::post('/webhooks/coinstack', CoinStackWebhookController::class);
// bootstrap/app.php (Laravel 13)
->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        'webhooks/coinstack',
    ]);
})

Laravel 13 renamed the middleware to PreventRequestForgery, and the CSRF documentation uses preventRequestForgery(except: [...]). On Laravel 11 and 12, call validateCsrfTokens(except: [...]) instead; in Laravel 13 that name still works but is marked deprecated. Laravel's docs also suggest the alternative of placing such routes outside the web group, for example in routes/api.php, which Laravel 11 and later create with php artisan install:api.

One testing gotcha: Laravel switches CSRF protection off while running tests, so a passing feature test proves nothing about this exception. Check it with a real request, such as Send test on the webhook in the dashboard.

Laravel: verify the signature on the raw body

The controller verifies first, then hands the work to a queue. $request->getContent() is the raw body. Do not rebuild it from $request->all(): json_encode writes https:// as https:\/\/, the bytes change, and the signature no longer matches.

<?php
// app/Http/Controllers/CoinStackWebhookController.php

namespace App\Http\Controllers;

use App\Jobs\SyncCoinStackCheckout;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CoinStackWebhookController extends Controller
{
    public function __invoke(Request $request)
    {
        $body = $request->getContent();

        if (! $this->verify((string) $request->header('CoinStack-Signature'), $body)) {
            return response('Invalid signature', 400);
        }

        $event = json_decode($body, true);
        $checkoutId = $event['data']['checkout']['checkout_id'] ?? null;

        if (! str_starts_with($event['kind'] ?? '', 'checkout.')
            || ! Order::where('checkout_id', $checkoutId)->exists()) {
            return response('', 200); // not one of our checkouts, such as the dashboard test event
        }

        DB::transaction(function () use ($event, $checkoutId) {
            $inserted = DB::table('coinstack_events')->insertOrIgnore([
                'event_id' => $event['event_id'],
                'kind' => $event['kind'],
            ]);

            if ($inserted === 1) {
                SyncCoinStackCheckout::dispatch($checkoutId);
            }
        });

        return response('', 200);
    }

    private function verify(string $header, string $body): bool
    {
        $parts = [];

        foreach (explode(',', $header) as $part) {
            $pair = explode('=', $part, 2);

            if (count($pair) === 2) {
                $parts[$pair[0]] = $pair[1];
            }
        }

        $timestamp = $parts['t'] ?? '';
        $expected = hash_hmac('sha256', $timestamp.'.'.$body, config('services.coinstack.webhook_secret'));

        return ctype_digit($timestamp)
            && hash_equals($expected, $parts['v1'] ?? '')
            && abs(time() - (int) $timestamp) <= 300;
    }
}

The coinstack_events table has event_id as its primary key, so insertOrIgnore returns 0 for an event already seen and the job is dispatched only once per event. event_id stays the same across retries and resends. If you prefer the check as middleware, how to verify payment webhooks has a Laravel middleware version and explains each step.

Schema::create('coinstack_events', function (Blueprint $table) {
    $table->uuid('event_id')->primary();
    $table->string('kind');
    $table->timestamp('received_at')->useCurrent();
});

Laravel: queue the work

The job does the slow part after the 200 has gone back. It reads the checkout's current status from the API, then claims the order inside a locked transaction:

<?php
// app/Jobs/SyncCoinStackCheckout.php

namespace App\Jobs;

use App\Models\Order;
use App\Services\CoinStack;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

class SyncCoinStackCheckout implements ShouldQueue
{
    use Queueable;

    public $tries = 5;

    public $backoff = [10, 60, 300, 900];

    public function __construct(public string $checkoutId)
    {
    }

    public function handle(CoinStack $coinstack): void
    {
        $checkout = $coinstack->getCheckout($this->checkoutId)['checkout'];

        if (! in_array($checkout['status'], ['completed', 'resolved'], true)) {
            return;
        }

        DB::transaction(function () use ($checkout) {
            $order = Order::where('checkout_id', $checkout['checkout_id'])->lockForUpdate()->first();

            if (! $order || $order->status !== 'unpaid') {
                return;
            }

            $order->update(['status' => 'paid']);

            // Fulfil here: send the email, provision the service, ship the box.
        });
    }
}

New Laravel applications use the database queue driver (QUEUE_CONNECTION=database) and ship the migration for its jobs table. Run php artisan queue:work under Supervisor or systemd so it restarts. With the database driver on the same connection, the event row and the queued job commit together. On Redis or SQS, add ->afterCommit() to the dispatch so the job never runs before the transaction that recorded the event.

If the API call fails, the job throws and Laravel retries it after 10 seconds, 1 minute, 5 minutes and 15 minutes. If it still fails, it lands in failed_jobs, which is the thing to alert on. A periodic sync of unpaid orders catches anything the webhook never delivered; reliable payment webhooks covers that poll and the delivery alerts.

How do you test it end to end?

A feature test with Http::fake() and a request you sign yourself covers the logic:

$body = json_encode([
    'event_id' => 'e41b7c92-3a5d-4f8e-b1c6-9d2a7f4e0b85',
    'kind' => 'checkout.completed',
    'data' => ['checkout' => ['checkout_id' => 'chk-1']],
]);
$t = time();
$signature = hash_hmac('sha256', $t.'.'.$body, 'whsec_test');

$this->call('POST', '/webhooks/coinstack', [], [], [], [
    'HTTP_COINSTACK_SIGNATURE' => "t=$t,v1=$signature",
    'CONTENT_TYPE' => 'application/json',
], $body)->assertOk();

The last step is a real payment. The smallest checkout is worth 1 US dollar; pay one with USDC on a low-cost network and watch the order change. Testing a crypto checkout lists the other cases worth paying for, such as a partial payment.

Frequently asked questions

Which PHP version does this need?

The plain PHP version uses cURL, hash_hmac and hash_equals, which every supported PHP release has. The typed function signatures need PHP 7.1 or later. The Laravel code targets Laravel 13, whose composer.json requires PHP 8.3 or later; on Laravel 11 or 12, the only change is the CSRF method name.

Why does my Laravel app return 419 to CoinStack webhooks?

419 is Laravel's response to a failed CSRF check. Webhook routes in routes/web.php must be listed in preventRequestForgery(except: [...]) on Laravel 13, or validateCsrfTokens(except: [...]) on Laravel 11 and 12, or moved outside the web middleware group. Feature tests will not show the problem, because Laravel disables CSRF checks while tests run.

How do I avoid creating two checkouts for the same order?

Save checkout_id on the order as soon as the checkout is created, and reuse it while that checkout is still pending. If a create request times out, list checkouts by the reference you sent before retrying. If the customer abandons the order, expire the checkout; only pending or partial checkouts can be expired. A payment that still arrives afterwards is recorded and can complete the checkout with late set, so decide what your handler does with an order you already cancelled.

Should I build my own payment page instead of redirecting?

Yes, if you want the customer to stay on your own site. The redirect gives you the hosted page, with token choice, address, amount, QR code and live status. Building your own uses the tokens and quotes endpoints, which building a custom crypto checkout walks through.

More posts