Search by

caravelpay / caravel-php

caravelpay

Caravel Pay PHP SDK: hosted card and crypto checkouts that pay out in USDC on Polygon, signed requests and webhook verification.

v1.2.2 2026-11-26 17:45 UTC

This package is auto-updated.

Last update: 2026-11-26 17:50:02 UTC


README

caravelpay/caravel-php: hosted card, Apple Pay, Google Pay and crypto checkouts that pay out to your own Polygon wallet, minus the 2% Caravel fee.

Your buyer pays the order total. Most card providers keep their own fee out of it, the Caravel fee is 2% of the order total, and you receive the rest.

  • PHP 7.4 to 8.5, no dependencies beyond ext-curl and ext-json.
  • Every request signed for you (Caravel-Merchant, Caravel-Timestamp, Caravel-Signature).
  • Webhook verification: constant-time HMAC, ±300 s window, callback path + query.
  • Responses validated, so a malformed answer can never mark an order paid.
  • Tested against the official signature vectors.

Docs: https://caravelpay.app/docs/php-sdk · API reference: https://caravelpay.app/docs/

Install

With Composer:

composer require caravelpay/caravel-php

Without Composer, download caravel-php-1.2.2.zip, unzip it into your project and require the bundled autoloader:

require __DIR__ . '/caravel-php/autoload.php';

Get API keys

There are no accounts or dashboards. One unsigned call returns a merchant id and secret. Run it once and store the result on your server:

$credentials = CaravelPay\Client::connect([
    'site_url' => 'https://shop.example',          // your return/cancel/callback URLs must be on this site
    'payout_address' => '0xYourPolygonWallet',
    'email' => 'you@shop.example',                  // optional, for operational notices
]);
// ['merchant_id' => 'mch_…', 'secret' => '…', 'status' => 'active', 'fee_rate' => '2%']

examples/connect.php does the same from the command line. Every call creates a new merchant. To change the payout wallet or rotate the secret, connect again and keep the old credentials until the old merchant's open checkouts have finished, because their webhooks stay signed with the old secret.

Create a checkout

use CaravelPay\Amount;
use CaravelPay\Client;

$caravel = new Client(getenv('CARAVEL_MERCHANT_ID'), getenv('CARAVEL_SECRET'));

$checkout = $caravel->createCheckout([
    'order_id' => '1042',
    'amount' => Amount::normalize($order->total),    // "136.41"; floats and "49.9" are converted
    'customer_email' => 'buyer@example.com',          // optional
    'return_url' => 'https://shop.example/thanks',
    'cancel_url' => 'https://shop.example/cart',
    'callback_url' => 'https://shop.example/webhooks/caravel',
]);
header('Location: ' . $checkout['checkout_url'], true, 303);

The same order_id with the same details returns the same checkout, so retries never make a second one. A checkout expires after 60 minutes. To let the buyer try again after that, use a new order_id such as 1042-2.

Handle the webhook

use CaravelPay\Checkout;
use CaravelPay\Exception\SignatureVerificationException;
use CaravelPay\Webhook;

try {
    $event = Webhook::verifyCurrentRequest($secret, 'https://shop.example/webhooks/caravel');
} catch (SignatureVerificationException $e) {
    http_response_code($e->getHttpStatus());   // 401, or 400 for a malformed event
    exit;
}
// Re-fetch: the webhook says what to look at, the signed API says what is true.
$checkout = $caravel->getCheckout($event->checkoutId());
if (Checkout::isPaid($checkout)) {
    mark_paid($checkout['order_id'], Checkout::txHash($checkout));
}
http_response_code(200);
  • $secret can be one secret, an array of merchant id ⇒ secret (keep replaced credentials there for a while), or a callable fn(string $merchantId): ?string.
  • The callback URL is the callback_url you registered (or its path). The signature covers its path and query string. Pass an array if the same endpoint is reachable under several URLs.
  • Skip duplicates by remembering $event->id: retries keep the same id.
  • Answer 2xx only after you've stored the result. Anything else is retried for 24 hours.

examples/webhook.php is a complete endpoint.

Reference

Method API Returns
Client::connect(array $params, array $options = []) POST /v1/connect (unsigned, never retried) merchant_id, secret, status, fee_rate
$client->createCheckout(array $params, ['idempotency_key' => …]) POST /v1/checkouts id, checkout_url, status, amount, currency, expires_at
$client->getCheckout(string $id) GET /v1/checkouts/{id} the checkout, with paid_amount and payout once paid
$client->listCheckouts(['limit' => 50, 'cursor' => …]) GET /v1/checkouts data[], next_cursor
$client->allCheckouts(['limit' => 100]) pages through GET /v1/checkouts a generator of checkouts
$client->getMerchant() GET /v1/merchant id, site_url, origins[], payout_address, status, fee_rate
$client->createPaymentLink(array $params) POST /v1/payment-links (signed, never retried) the payment link
Client::createPaymentLinkWithoutKeys(array $params) POST /v1/payment-links unsigned, with payout_address id, url
$client->getPaymentLink(string $id) GET /v1/payment-links/{id} the payment link
$client->deactivatePaymentLink(string $id) POST /v1/payment-links/{id}/deactivate the deactivated link
$client->request($method, $path, ?array $body) any signed endpoint decoded JSON
$client->lastStatus() HTTP status of the last response (201 new / 200 existing checkout)
Webhook::verify($body, $headers, $secrets, $callbackUrl, $options) Event (id, type, created, data, merchantId)
Webhook::verifyCurrentRequest($secrets, $callbackUrl) reads php://input and $_SERVER Event
Webhook::signTestEvent($merchantId, $secret, $callbackUrl, $body) headers for a signed test event to your own endpoint
Signature::compute(), ::headers(), ::matches(), ::signedPath() the signing primitives
Checkout::STATUSES, ::isPaid(), ::txHash(), ::payouts(), ::explorerUrl(), ::feeMode(), ::buyerTotalEstimate() checkout helpers
FeeMode::SELLER, ::SPLIT, ::BUYER, ::labels(), ::buyerNotice(), ::apply() who pays the fees
$client->fxQuote(string $currency, ?string $amount) GET /v1/fx-quote currency, fx_rate, quoted_at, and usd_amount with an amount
Currency::DECIMALS, ::isSupported(), ::format(), ::estimateUsd(), ::buyerNotice(), ::bufferBps() other currencies
Checkout::usdAmount(), ::fxRate() a checkout's order total in US dollars and its rate
Amount::normalize(), ::toCents(), ::compare(), ::equals() exact two-decimal amounts

Client options: api_base (default https://api.caravelpay.app; http:// only for localhost), timeout (15 s), connect_timeout (10 s), max_retries (0), user_agent (a product token such as MyShop/2.1, put before the SDK's), ca_bundle, transport.

Who pays the fees

By default you absorb both fees. Send fee_mode to pass them on:

use CaravelPay\Checkout;
use CaravelPay\FeeMode;

$checkout = $caravel->createCheckout([
    'order_id' => '1043',
    'amount' => '100.00',
    'return_url' => 'https://shop.example/thanks',
    'cancel_url' => 'https://shop.example/cart',
    'callback_url' => 'https://shop.example/webhooks/caravel',
    'fee_mode' => FeeMode::BUYER,
]);
$checkout['amount'];                          // "100.00": always your own order total
Checkout::buyerTotalEstimate($checkout);      // "102.04": what the buyer pays before the card provider's fee
fee_mode card provider's fee 2% Caravel fee on a $100.00 order you receive
seller (default) you you what arrives minus $2.00
split the buyer you $98.00
buyer the buyer the buyer $100.00
  • Without fee_mode, your merchant default applies: seller, unless you passed fee_mode to Client::connect().
  • A seller checkout carries no fee_mode; Checkout::feeMode() returns "seller" for it.
  • The mode is fixed when the checkout is created. The same order_id with another mode fails with order_id_conflict.
  • For a settings screen: FeeMode::labels() gives the three option labels, FeeMode::buyerNotice($mode) a line to show buyers, and FeeMode::apply($body, $saved) adds fee_mode only when the setting isn't the default.
  • Card surcharges are restricted in some countries (for example on consumer cards in the EU and the UK). Check your local rules before passing fees on.

Other currencies

Price the checkout in your store's own currency. It is converted to US dollars once, when the checkout is created, and that amount is fixed for the checkout. Buyers are always charged in US dollars; you are always paid in USDC.

use CaravelPay\Checkout;
use CaravelPay\Currency;

$checkout = $caravel->createCheckout([
    'order_id' => '1044',
    'amount' => Currency::format($order->total, 'EUR'),   // "45.00"; Currency::format(5000, 'JPY') is "5000"
    'currency' => 'EUR',
    'return_url' => 'https://shop.example/thanks',
    'cancel_url' => 'https://shop.example/cart',
    'callback_url' => 'https://shop.example/webhooks/caravel',
]);
$checkout['amount'];                 // "45.00", and $checkout['currency'] is "EUR": exactly what you sent
Checkout::usdAmount($checkout);      // "48.60": your order total in US dollars, fixed for this checkout
Checkout::fxRate($checkout);         // "1.08": US dollars for one euro when it was created
  • Supported besides USD: EUR, GBP, CAD, AUD, NZD, SEK, NOK, DKK, CHF, PLN, CZK, HUF, RON, HKD, SGD, MXN, BRL, ZAR, ILS, INR, THB, MYR, PHP, TRY (two decimals) and JPY, KRW (no decimals). Currency::DECIMALS has the list.
  • Mark an order paid from the checkout's status. Compare amount and currency with what you sent, in your own currency; paid_amount and the payout are US dollars and tokens, so compare those with Checkout::usdAmount().
  • A retry with the same order_id, amount and currency returns the same checkout with its original rate.
  • If no exchange rate can be confirmed, the API answers 503 service_unavailable and creates nothing. Retry with the same order_id.
  • To tell buyers what to expect before you redirect them, cache a rate for a few minutes and build the line:
$quote = $caravel->fxQuote('EUR');                                             // ['currency' => 'EUR', 'fx_rate' => '1.08', …]
echo Currency::buyerNotice('EUR', Currency::estimateUsd('45.00', 'EUR', $quote['fx_rate']));
// You'll be charged in US dollars: about $48.60. You see the exact amount before you pay.
  • Optional 'fx_buffer_bps' => 100 adds a 1% margin to the converted amount (0 to 500), to cover exchange-rate movement until you convert your USDC. Currency::bufferBps('1.5') turns a percentage setting into basis points.

Statuses

status meaning what to do
awaiting_payment open, nothing arrived yet wait
confirming a payment is confirming wait; don't ship yet
paid full amount arrived and both payout transfers confirmed mark paid with Checkout::txHash()
underpaid less than the amount arrived; the buyer can top up hold, note paid_amount
expired passed expires_at without payment cancel if unpaid
review needs a manual look hold

Late transitions exist: underpaid → paid, expired → paid, any → review.

Errors

Exception When
Exception\ApiException Non-2xx answer. getErrorCode() (for example order_id_conflict), getHttpStatus(), getParam(), getRetryAfter(), isRetryable()
Exception\NetworkException No HTTP response (DNS, TLS, timeout). Retrying createCheckout with the same order_id is safe
Exception\UnexpectedResponseException A 2xx with a malformed body. Treat as failed
Exception\SignatureVerificationException A webhook failed verification. getReason(), getHttpStatus()

All four extend Exception\CaravelPayException. Mistakes in arguments throw \InvalidArgumentException before any request is sent.

With max_retries > 0, GETs and createCheckout are retried on network errors, 429 and 5xx: after Retry-After when it is 10 s or less, otherwise with 250 ms → 500 ms → 1 s backoff. Each retry is re-signed. connect and other POSTs are never retried.

Using your platform's HTTP client

Implement CaravelPay\Http\TransportInterface (one send() method) and pass it as transport. A transport must verify TLS, must not follow redirects, and must throw NetworkException when there is no response.

Vendoring into a plugin or module

Copy src/, autoload.php and LICENSE into your module (for example lib/caravel-php/) and require_once the autoloader. If two plugins in one PHP process ship the SDK, the first one loaded wins, so keep vendored copies on the same version.

Coming from PayGate's PHP SDK

PayGate's SDK builds a payment URL from a wallet-forwarding address and verifies its callback. With Caravel Pay you create a checkout object for each order, redirect to its checkout_url and verify a signed webhook. Then you re-fetch the checkout before marking the order paid. There is no per-order address to generate and no amount tolerance setting: underpaid is reported as its own status. The payout goes to the wallet you connected, in the token the buyer paid with (card payments arrive as USDC), minus the 2% Caravel fee.

Download

Docs and support

Licence

MIT. See LICENSE.