PHP code example of gobtcpay / php-merchant-sdk

1. Go to this page and download the library: Download gobtcpay/php-merchant-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/ */

    

gobtcpay / php-merchant-sdk example snippets


use GoBTCPay\PosApiSdk\GoBTCPay;

$btcPay = new GoBTCPay(
    apiKey: getenv('POS_API_KEY'),
    posTerminalId: getenv('POS_TERMINAL_ID'),
);

// Create a payment and show the QR to the customer.
$payment = $btcPay->createPayment(
    amount: 10,
    currency: 'USD',
    description: 'Order #1024',
);
echo $payment->paymentId, PHP_EOL;
echo $payment->qrString, PHP_EOL;

// Fetch the current state.
$latest = $btcPay->getPayment($payment->paymentId);
echo $latest->status->value; // initiated | detected | paid | expired | canceled | failed | cleared

use GoBTCPay\PosApiSdk\GoBTCPayServer;

$gobtcpay = new GoBTCPayServer(apiKey: getenv('GOBTCPAY_SECRET_KEY'));

$payment = $gobtcpay->createPayment(
    amount: 49.99,
    currency: 'USD',
    externalId: "order-{$order->id}", // makes create idempotent — pass it!
);

header('Location: ' . $payment->checkoutUrl);

use GoBTCPay\PosApiSdk\GoBTCPayServer;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;

$factory = new HttpFactory();
$gobtcpay = new GoBTCPayServer(
    apiKey: getenv('GOBTCPAY_SECRET_KEY'),
    httpClient: new Client(['timeout' => 30]),
    requestFactory: $factory,
    streamFactory: $factory,
);

$btcPay->createPayment(amount, currency, posTerminalId?, description?, ttlSeconds?, externalId?): Payment;
$btcPay->getPayment(paymentId): Payment;
$btcPay->watchPayment(['paymentId' => ..., 'intervalMs' => ..., 'timeoutMs' => ..., 'until' => [...], 'immediate' => ..., 'stopOnError' => ...]): PaymentPoller;
$btcPay->webhooks(signingSecret, toleranceSeconds?, dedupeCacheSize?): WebhookHandler;

$gobtcpay->createPayment(amount, currency, externalId?, description?, ttlSeconds?): Payment;
$gobtcpay->getPayment(paymentId): Payment;
$gobtcpay->cancelPayment(paymentId): Payment;
$gobtcpay->listPayments(status?, externalId?, dateRange?, limit?): Generator<PaymentListItem>;
$gobtcpay->listPaymentsPage(status?, externalId?, dateRange?, limit?, skip?): array{items: PaymentListItem[], totalCount: int};
$gobtcpay->watchPayment([...]): PaymentPoller;
$gobtcpay->listWebhooks(status?, limit?, skip?): array{items: WebhookEndpoint[], totalCount: int};
$gobtcpay->testWebhook(webhookId): void;
$gobtcpay->webhooks(signingSecret, toleranceSeconds?, dedupeCacheSize?): WebhookHandler;

use GoBTCPay\PosApiSdk\Dto\PaymentStatus;

foreach ($gobtcpay->listPayments(status: [PaymentStatus::Paid]) as $item) {
    $this->reconcile($item);
}

$poller = $btcPay->watchPayment(['paymentId' => $payment->paymentId, 'intervalMs' => 3000]);

$poller->onChange(fn ($status) => render($status));   // any status change
$poller->onUpdate(fn ($payment) => {});               // every successful poll
$poller->onPaid(fn ($payment) => {});                 // transition into `paid`
$poller->onSettled(fn ($payment) => {});              // the poller stopped (see the note below)
$poller->onError(fn ($error) => {});                  // a poll failed

$final = $poller->poll(); // blocks, returns the settled Payment

$webhooks = $gobtcpay->webhooks(getenv('POS_WEBHOOK_SECRET'));

$webhooks->on('payment.status.updated', function ($event) {
    if (!$event->hasPaymentData()) {
        return;                              // a test delivery — nothing to update
    }

    $payment = $event->payment();            // typed Payment
    // $event->data is also the raw decoded array
    error_log("{$payment->paymentId} -> {$payment->status->value}");
});

foreach ($gobtcpay->listWebhooks()['items'] as $endpoint) {
    echo $endpoint->url, ' ', $endpoint->status, PHP_EOL;
}

$gobtcpay->testWebhook($endpointId);

$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_GOBTCPAY_SIGNATURE'] ?? null;

try {
    $webhooks->handle($rawBody, $signature);
    http_response_code(200); // any 2xx acknowledges; non-2xx is retried
} catch (\GoBTCPay\PosApiSdk\Exception\WebhookSignatureException) {
    http_response_code(400);
}

use Illuminate\Http\Request;

Route::post('/webhooks/gobtcpay', function (Request $request) use ($webhooks) {
    try {
        $webhooks->handle(
            $request->getContent(), // RAW body
            $request->header('X-GoBTCPay-Signature'),
        );
        return response()->noContent(); // 204
    } catch (\GoBTCPay\PosApiSdk\Exception\WebhookSignatureException) {
        return response('invalid signature', 400);
    }
});

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

#[Route('/webhooks/gobtcpay', methods: ['POST'])]
public function gobtcpay(Request $request): Response
{
    try {
        $this->webhooks->handle(
            $request->getContent(), // RAW body
            $request->headers->get('X-GoBTCPay-Signature'),
        );
        return new Response('', Response::HTTP_NO_CONTENT);
    } catch (\GoBTCPay\PosApiSdk\Exception\WebhookSignatureException) {
        return new Response('invalid signature', Response::HTTP_BAD_REQUEST);
    }
}

use GoBTCPay\PosApiSdk\Exception\ApiException;
use GoBTCPay\PosApiSdk\Exception\NetworkException;
use GoBTCPay\PosApiSdk\Exception\RateLimitException;

try {
    $payment = $gobtcpay->createPayment(amount: 10, currency: 'USD', externalId: 'order-1');
} catch (RateLimitException $e) {
    // back off for $e->retryAfterMs
} catch (ApiException $e) {
    error_log("API {$e->httpStatus} ({$e->requestId}): {$e->getMessage()}");
} catch (NetworkException $e) {
    // connection failure / timeout ($e->isTimeout)
}
bash
composer