PHP code example of detain / coinbase-commerce

1. Go to this page and download the library: Download detain/coinbase-commerce 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/ */

    

detain / coinbase-commerce example snippets

 php
use CoinbaseCommerce\ApiClient;

//Make sure you don't store your API Key in your source code!
$apiClientObj = ApiClient::init(<API_KEY>);
$apiClientObj->setTimeout(3);
 php
$apiClientObj->verifySsl(false);
 php
use CoinbaseCommerce\ApiClient;

//Make sure you don't store your API Key in your source code!
$apiClientObj = ApiClient::init(<API_KEY>);
$apiClientObj->setLogger($logger);
 php
$checkoutObj = Checkout::retrieve(<checkout_id>);
 php
$checkoutObj = new Checkout();

$checkoutObj->id = <checkout_id>;
$checkoutObj->delete();

// or

Checkout::deleteById(<checkout_id>);
 php
$params = [
    'limit' => 2,
    'order' => 'desc'
];

$list = Checkout::getList($params);

foreach($list as $checkout) {
    var_dump($checkout);
}

// Get number of items in list
$count = $list->count();

// or
$count = count($list);

// Get number of all checkouts
$countAll = $list->countAll();

// Get pagination
$pagination = $list->getPagination();

// To load next page with previous setted params(in this case limit, order)
if ($list->hasNext()) {
    $list->loadNext();
    
    foreach($list as $checkout) {
        var_dump($checkout);
    }
}

 php
$params = [
    'order' => 'desc'  
];

$allCheckouts = Checkout::getAll($params);

 php
$chargeObj = Charge::retrieve(<charge_id>);
 php
$chargeData = [
    'name' => 'The Sovereign Individual',
    'description' => 'Mastering the Transition to the Information Age',
    'local_price' => [
        'amount' => '100.00',
        'currency' => 'USD'
    ],
    'pricing_type' => 'fixed_price'
];
Charge::create($chargeData);

// or
$chargeObj = new Charge();

$chargeObj->name = 'The Sovereign Individual';
$chargeObj->description = 'Mastering the Transition to the Information Age';
$chargeObj->local_price = [
    'amount' => '100.00',
    'currency' => 'USD'
];
$chargeObj->pricing_type = 'fixed_price';
$chargeObj->save();
 php
$list = Charge::getList();

foreach($list as $charge) {
    var_dump($list);
}

$pagination = $list->getPagination();
 php
$allCharges = Charge::getAll();
 php
$invoiceObj = Invoice::retrieve(<invoice_id>);
 php
$list = Invoice::getList();

foreach($list as $invoice) {
    var_dump($list);
}

$pagination = $list->getPagination();
 php
$allInvoices = Invoice::getAll();
 php
$eventObj = Event::retrieve(<event_id>);
 php
$listEvent = Event::getList();

foreach($listEvent as $event) {
    var_dump($event);
}

$pagination = $listEvent->getPagination();
 php
$allEvents = Event::getAll();
 php
use CoinbaseCommerce\Webhook;

try {
    Webhook::verifySignature($signature, $body, $sharedSecret);
    echo 'Successfully verified';
} catch (\Exception $exception) {
    echo $exception->getMessage();
    echo 'Failed';
}
 php
$result = PaymentLink::create([
    'amount' => '100.00',
    'currency' => 'USDC',
    'description' => 'Payment for order #12345',
    'successRedirectUrl' => 'https://example.com/success',
    'failRedirectUrl' => 'https://example.com/failed',
    'metadata' => [
        'orderId' => '12345',
        'customerId' => 'cust_abc123',
    ],
]);

echo "Payment URL: {$result['url']}\n";
echo "Status: {$result['status']}\n"; // ACTIVE
 php
$link = PaymentLink::get($linkId);
echo "Status: {$link['status']}\n";
 php
$list = PaymentLink::list([
    'pageSize' => 10,
    'status' => 'ACTIVE',
]);

foreach ($list['paymentLinks'] as $link) {
    echo "{$link['id']}: {$link['status']}\n";
}
 php
$deactivated = PaymentLink::deactivate($linkId);
echo "Status: {$deactivated['status']}\n"; // DEACTIVATED
 php
$result = PaymentLink::create($params, 'unique-request-id-123');
 php
use CoinbaseCommerce\PaymentLink\PaymentLinkWebhook;

$payload = file_get_contents('php://input');
$signatureHeader = $_SERVER['HTTP_X_HOOK0_SIGNATURE'] ?? '';

// Collect request headers (normalized to lowercase keys)
$headers = [];
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $headerName = strtolower(str_replace('_', '-', substr($key, 5)));
        $headers[$headerName] = $value;
    }
}
$headers['content-type'] = $_SERVER['CONTENT_TYPE'] ?? 'application/json';

try {
    // Verifies signature, checks replay protection (5 min default), then parses JSON
    $event = PaymentLinkWebhook::buildEvent($payload, $signatureHeader, $webhookSecret, $headers);

    switch ($event['eventType']) {
        case 'payment_link.payment.success':
            // Fulfill the order
            break;
        case 'payment_link.payment.failed':
            // Handle failure
            break;
        case 'payment_link.payment.expired':
            // Handle expiry
            break;
    }

    http_response_code(200);
} catch (\CoinbaseCommerce\Exceptions\SignatureVerificationException $e) {
    http_response_code(400);
}