disputeguard / disputeguard-php
PHP client for the DisputeGuard Connect API: push orders and activity evidence, answer runtime evidence requests, read disputes and verify webhooks.
Requires
- php: >=8.1
- ext-json: *
- guzzlehttp/guzzle: ^7.5
Requires (Dev)
- phpunit/phpunit: ^10.5 || ^11.0
Suggests
- psr/http-message: Use EvidenceRequestHandler::handlePsr7() with PSR-7 frameworks (installed with Guzzle)
Provides
None
Conflicts
None
Replaces
None
README
disputeguard/disputeguard-php is the official PHP client for the DisputeGuard Connect API. Use it to
turn any PHP app (a SaaS, a custom store, a membership site…) into a DisputeGuard source:
- push orders and activity events ahead of time so disputes are matched and fought automatically,
- answer signed runtime evidence requests (
evidence.requested) when a dispute lands, - read disputes, push evidence and files, and manage outbound webhook endpoints,
- verify
X-DisputeGuard-Signatureon webhooks you receive.
Requires PHP 8.1+ and Guzzle 7.
composer require disputeguard/disputeguard-php
You need a source token: sign up at https://app.disputeguard.com/register, then Sources → Custom app / API → Create source. New to DisputeGuard? The quickstart takes you from a token to your first order, event and test dispute.
Quick start
use DisputeGuard\Client; use DisputeGuard\Event; $dg = new Client(getenv('DISPUTEGUARD_TOKEN')); // dg_live_… from Sources → Custom app / API $dg->source()->get(); // connection check: throws AuthenticationException on a bad token $dg->orders()->upsert([ 'external_id' => '1042', 'amount' => 4999, // minor units (cents) 'currency' => 'usd', 'placed_at' => new DateTimeImmutable(), // DateTimeInterface is serialized to ISO-8601 UTC 'customer' => ['email' => 'jane@example.com', 'ip' => '203.0.113.7'], 'payment' => ['processor' => 'stripe', 'charge_id' => 'ch_3P…', 'payment_intent_id' => 'pi_3P…'], ]); $dg->events()->create( Event::shipped('ups', '1Z999AA10123456784')->forOrder('1042')->idempotencyKey('ship-1042') );
Client options
new Client($token, [ 'base_url' => 'https://app.disputeguard.com/api/v1', // default; use {APP_URL}/api/v1 for self-hosted/dev 'timeout' => 30, // seconds 'connect_timeout' => 10, // seconds 'max_retries' => 2, // for 429 / 5xx / network errors (see "Retries") 'handler' => $guzzleHandlerStack, // optional, e.g. a MockHandler in tests 'http_client' => $guzzleClient, // optional, a preconfigured GuzzleHttp\ClientInterface ]);
API surface
| Call | Endpoint | Returns |
|---|---|---|
Client::exchangeConnectCode($code, $options) |
POST /connect/exchange (no auth) |
['token', 'signing_secret', 'source'] |
Client::connectUrl($params, $options) / Client::generateState() |
builds GET {APP_URL}/connect/{platform}?… |
string |
$dg->source()->get() |
GET /source |
Source |
$dg->source()->update($params) |
PATCH /source |
Source |
$dg->orders()->upsert($order) |
POST /orders |
Order |
$dg->orders()->upsertMany($orders) |
POST /orders/batch (chunked by 100) |
list<Order> |
$dg->orders()->get($externalId) |
GET /orders/{external_id} |
Order |
$dg->events()->create($eventOrEvents) |
POST /events (chunked by 100) |
['created' => int, 'duplicates' => int] |
$dg->disputes()->list($params) |
GET /disputes |
['data' => list<Dispute>, 'meta' => …] |
$dg->disputes()->iterate($params) |
GET /disputes (all pages, lazily) |
Generator<Dispute> |
$dg->disputes()->get($id) |
GET /disputes/{id} |
Dispute |
$dg->disputes()->submitEvidence($id, $evidence) |
POST /disputes/{id}/evidence |
Dispute |
$dg->disputes()->uploadFile($id, $kind, $file, $options) |
POST /disputes/{id}/files (multipart) |
EvidenceFile |
$dg->webhookEndpoints()->list() |
GET /webhook-endpoints |
['data' => list<WebhookEndpoint>] |
$dg->webhookEndpoints()->create($params) |
POST /webhook-endpoints |
WebhookEndpoint + secret |
$dg->webhookEndpoints()->delete($id) |
DELETE /webhook-endpoints/{id} |
void |
Webhook::constructEvent($rawBody, $sigHeader, $secret, $tolerance = 300) |
— | decoded event array |
Webhook::sign($rawBody, $secret, $timestamp = null) |
— | signature header (for tests) |
new EvidenceRequestHandler($secret, $callback) |
— | runtime callback helper |
Responses are decoded JSON arrays with the exact shape of the OpenAPI schemas (API reference).
Everywhere an Event or Evidence builder is accepted, the equivalent plain array works too.
Errors
All exceptions extend DisputeGuard\Exception\DisputeGuardException.
| Exception | When |
|---|---|
ApiException |
Any non-2xx response. getStatus(), getMessage(), getErrors() (field → messages), getBody() |
├ AuthenticationException |
401 — missing/invalid/revoked token |
├ PermissionException |
403 — token not allowed to do this |
├ NotFoundException |
404 |
├ ConflictException |
409 — evidence already submitted to the processor |
├ ValidationException |
422 — see getErrors(), e.g. ['orders.0.amount' => ['The amount field is required.']] |
└ RateLimitException |
429 after retries — getRetryAfter() |
ApiConnectionException |
No HTTP response (DNS, timeout, TLS…) |
SignatureVerificationException |
Webhook/callback signature missing, invalid or outside tolerance |
try { $dg->orders()->upsert($payload); } catch (DisputeGuard\Exception\ValidationException $e) { error_log(json_encode($e->getErrors())); }
Retries
- 429 responses are retried for every call (the request was not processed), waiting for
Retry-After(up to 60 s; longer waits throwRateLimitExceptionimmediately so web requests don't hang). - 5xx, 408 and network errors are retried with exponential backoff (0.5 s, 1 s, … with jitter) only for
calls that are safe to repeat:
GET,DELETE,PATCH /source, order upserts, andevents()->create()when every event has anidempotency_key. Evidence pushes, file uploads, endpoint creation and the connect code exchange are never retried on 5xx. max_retries(default 2) caps the number of retries.
Custom integration walkthrough
The end-to-end flow for a custom app. Store the source token and signing_secret in your config/secrets.
0. Connect (one-click) — optional
Skip this if you create the source in the dashboard (Sources → New source) and paste the token.
// GET /disputeguard/connect — send the merchant to DisputeGuard $state = Client::generateState(); $_SESSION['dg_state'] = $state; header('Location: ' . Client::connectUrl([ 'platform' => 'custom', 'site_url' => 'https://shop.example.com', 'site_name' => 'Example Shop', 'return_url' => 'https://shop.example.com/disputeguard/return', 'state' => $state, ])); // GET /disputeguard/return?code=…&state=… if (!hash_equals($_SESSION['dg_state'] ?? '', $_GET['state'] ?? '')) { http_response_code(400); exit('Invalid state'); } $creds = Client::exchangeConnectCode($_GET['code']); // single-use, valid 10 minutes saveSecret('DISPUTEGUARD_TOKEN', $creds['token']); saveSecret('DISPUTEGUARD_SIGNING_SECRET', $creds['signing_secret']); // Tell DisputeGuard where to send runtime evidence requests. (new Client($creds['token']))->source()->update([ 'callback_url' => 'https://shop.example.com/disputeguard/evidence', 'capabilities' => ['orders', 'events', 'runtime_evidence', 'files'], 'plugin_version' => '1.0.0', ]);
1. Push orders on checkout (and when they change)
Include every processor identifier you have — that's how disputes are matched to orders.
$dg = new Client(getenv('DISPUTEGUARD_TOKEN')); function orderPayload(Order $order): array { return [ 'external_id' => (string) $order->id, 'order_number' => $order->number, 'status' => 'processing', 'amount' => $order->total_cents, 'currency' => 'usd', 'placed_at' => $order->created_at, 'admin_url' => "https://shop.example.com/admin/orders/{$order->id}", 'customer' => [ 'external_id' => (string) $order->user_id, 'email' => $order->email, 'name' => $order->name, 'account_created_at' => $order->user->created_at, 'ip' => $order->ip, 'user_agent' => $order->user_agent, ], 'billing_address' => ['line1' => '1 Main St', 'city' => 'Austin', 'state' => 'TX', 'postal_code' => '78701', 'country' => 'US'], 'shipping_address' => ['line1' => '1 Main St', 'city' => 'Austin', 'state' => 'TX', 'postal_code' => '78701', 'country' => 'US'], 'payment' => [ 'processor' => 'stripe', 'charge_id' => $order->stripe_charge_id, 'payment_intent_id' => $order->stripe_payment_intent_id, 'customer_id' => $order->stripe_customer_id, 'card_brand' => 'visa', 'card_last4' => '4242', 'avs_postal_check' => 'pass', 'cvc_check' => 'pass', 'three_d_secure' => 'authenticated', ], 'items' => [ ['name' => 'Pro plan (annual)', 'sku' => 'PRO-12', 'quantity' => 1, 'unit_amount' => 4999, 'type' => 'subscription'], ], ]; } $dg->orders()->upsert(orderPayload($order)); // Checkout context strengthens fraud/unrecognized disputes. $dg->events()->create( Event::checkoutCompleted(['terms_accepted' => true, 'terms_url' => 'https://shop.example.com/terms', 'timezone' => 'America/Chicago']) ->forOrder((string) $order->id) ->ip($order->ip) ->userAgent($order->user_agent) ->idempotencyKey("checkout-{$order->id}") ); // Backfill: upsertMany() chunks into /orders/batch requests of 100. $dg->orders()->upsertMany(array_map('orderPayload', $recentOrders));
Upserts are idempotent and omitted fields are left untouched, so send the order again when it is paid,
shipped or refunded (['external_id' => '1042', 'status' => 'refunded', 'refunded_amount' => 4999, …]).
2. Push events on shipment, delivery, login, usage…
// Shipment → strengthens "product not received" $dg->events()->create( Event::shipped('ups', $trackingNumber, "https://ups.com/track?num=$trackingNumber") ->forOrder('1042') ->idempotencyKey("ship-1042-$trackingNumber") ); // Logins are tied to a customer rather than an order → strengthens fraud/unrecognized $dg->events()->create( Event::login('password') ->forCustomer($user->email) ->ip($request->ip()) ->userAgent($request->userAgent()) ->idempotencyKey("login-{$sessionId}") ); // Many at once (arrays work too); lists over 100 are chunked automatically $dg->events()->create([ Event::downloadAccessed('ebook.pdf', 'The Book')->forOrder('1043')->at($downloadedAt), ['type' => 'usage.recorded', 'occurred_at' => '2026-09-30T12:00:00Z', 'customer_email' => 'jane@example.com', 'data' => ['metric' => 'emails_sent', 'quantity' => 1200], 'idempotency_key' => 'usage-2026-09-30-jane'], ]);
Builders exist for the whole vocabulary: checkoutCompleted, termsAccepted, paymentAuthorized,
accountCreated, login, shipped, delivered, downloadAccessed, serviceAccessed, usageRecorded,
message, refundIssued, refundDeclined, subscriptionRenewed, subscriptionCancelled,
policyAcknowledged, orderNote, plus Event::make($type, $data) for custom types. Always set an
idempotencyKey() — duplicates are ignored server-side and it lets the SDK safely retry 5xx errors.
3. Answer evidence.requested (runtime callback)
When a dispute lands, DisputeGuard POSTs a signed evidence.requested to your callback_url and waits
up to 20 seconds. Return evidence (200), defer and push it later (202), or say you have nothing (404):
// public/disputeguard-evidence.php — plain PHP require __DIR__ . '/../vendor/autoload.php'; use DisputeGuard\Client; use DisputeGuard\Event; use DisputeGuard\Evidence; use DisputeGuard\EvidenceRequest; use DisputeGuard\EvidenceRequestHandler; $handler = new EvidenceRequestHandler(getenv('DISPUTEGUARD_SIGNING_SECRET'), function (EvidenceRequest $req) { // data.order is null when DisputeGuard couldn't match; fall back to processor ids / email. $order = $req->orderExternalId() !== null ? Order::find($req->orderExternalId()) : Order::findByStripeCharge($req->chargeId(), $req->paymentIntentId()); if ($order === null) { return null; // 404 — no data for this dispute } if ($req->wants('communications') && $order->hasLargeTicketHistory()) { dispatchEvidenceJob($req->disputeId(), $order->id); // push later with submitEvidence() return EvidenceRequestHandler::accepted(); // 202 } return Evidence::make() // 200 + evidence ->order(orderPayload($order)) ->events(array_map( fn ($login) => Event::login()->forCustomer($order->email)->ip($login->ip)->at($login->at), $order->user->recentLogins() )) ->field('product_description', 'Pro plan, annual subscription to Example SaaS') ->field('refund_policy_disclosure', 'Shown and accepted at checkout: https://shop.example.com/refunds') ->priorTransaction(['order_external_id' => '998', 'charge_id' => 'ch_prev', 'placed_at' => '2026-03-01T10:00:00Z', 'amount' => 4999, 'currency' => 'usd', 'ip' => $order->ip]) ->file('receipt', storage_path("invoices/{$order->id}.pdf")); }); $handler->respond(); // reads php://input + headers, verifies the signature, emits the response
Handler behaviour:
- invalid/missing signature, stale timestamp (> 300 s), invalid JSON, or a type other than
evidence.requested→400 {"error": "…"}(your callback is not called); - callback returns an array /
Evidence→200with the JSON body; - callback returns
EvidenceRequestHandler::accepted()→202; - callback returns
null→404; - callback throws → the exception propagates (your framework answers 5xx and DisputeGuard retries).
Other entry points: $handler->handle($rawBody, $headers) returns [$status, $headers, $body] for any
framework; $handler->handlePsr7($serverRequest) returns a PSR-7 response (Slim, Mezzio, PSR-15…).
Deferred (202) answers — push the evidence from your queue worker:
$dg->disputes()->submitEvidence($disputeId, Evidence::make()->field('customer_communication', $transcript)); $dg->disputes()->uploadFile($disputeId, 'customer_communication', '/tmp/ticket-transcript.pdf', ['description' => 'Support ticket #881']);
Both throw ConflictException (409) once evidence has already been submitted to the processor.
4. Receive dispute.created (and other) webhooks
Register an endpoint once (or in the dashboard → Developers). The secret is returned once:
$endpoint = $dg->webhookEndpoints()->create([ 'url' => 'https://shop.example.com/disputeguard/webhooks', 'events' => ['dispute.created', 'dispute.updated', 'dispute.closed', 'evidence.ready', 'dispute.deadline_approaching'], 'description' => 'Ops alerts', ]); saveSecret('DISPUTEGUARD_WEBHOOK_SECRET', $endpoint['secret']);
Then verify and handle deliveries — always against the raw body:
use DisputeGuard\Webhook; use DisputeGuard\Exception\SignatureVerificationException; $raw = file_get_contents('php://input'); try { $event = Webhook::constructEvent($raw, $_SERVER['HTTP_X_DISPUTEGUARD_SIGNATURE'] ?? null, getenv('DISPUTEGUARD_WEBHOOK_SECRET')); } catch (SignatureVerificationException $e) { http_response_code(400); exit; } switch ($event['type']) { case 'dispute.created': $dispute = $event['data']['dispute']; notifySlack("New {$dispute['reason']} dispute for {$dispute['amount']} {$dispute['currency']}, due {$dispute['evidence_due_by']}"); break; case 'dispute.closed': markOrder($event['data']['dispute']['order']['external_id'] ?? null, $event['data']['dispute']['status']); break; } http_response_code(200); // non-2xx responses are retried with backoff
During secret rotation pass both secrets: Webhook::constructEvent($raw, $sig, [$newSecret, $oldSecret]).
Deliveries may be retried, so de-duplicate on $event['id'] (or the X-DisputeGuard-Delivery header).
Reading disputes
$page = $dg->disputes()->list(['status' => 'needs_response', 'per_page' => 50]); foreach ($dg->disputes()->iterate(['order_external_id' => '1042']) as $dispute) { echo $dispute['id'], ' ', $dispute['status'], ' ', $dispute['packet']['score'] ?? '-', PHP_EOL; }
Laravel
// config/services.php 'disputeguard' => [ 'token' => env('DISPUTEGUARD_TOKEN'), 'signing_secret' => env('DISPUTEGUARD_SIGNING_SECRET'), 'webhook_secret' => env('DISPUTEGUARD_WEBHOOK_SECRET'), ], // app/Providers/AppServiceProvider.php public function register(): void { $this->app->singleton(\DisputeGuard\Client::class, fn () => new \DisputeGuard\Client(config('services.disputeguard.token'))); } // app/Listeners/PushOrderToDisputeGuard.php (queued) public function handle(OrderPlaced $event): void { app(\DisputeGuard\Client::class)->orders()->upsert(OrderPayload::from($event->order)); } // routes/api.php (api routes have no CSRF middleware) use DisputeGuard\{Evidence, EvidenceRequest, EvidenceRequestHandler, Webhook}; use DisputeGuard\Exception\SignatureVerificationException; use Illuminate\Http\Request; Route::post('/disputeguard/evidence', function (Request $request) { $handler = new EvidenceRequestHandler(config('services.disputeguard.signing_secret'), function (EvidenceRequest $req) { $order = Order::where('id', $req->orderExternalId()) ->orWhere('stripe_charge_id', $req->chargeId()) ->first(); return $order ? Evidence::make()->order(OrderPayload::from($order)) : null; }); [$status, $headers, $body] = $handler->handle($request->getContent(), $request->headers->all()); return response($body, $status, $headers); }); Route::post('/disputeguard/webhooks', function (Request $request) { try { $event = Webhook::constructEvent( $request->getContent(), $request->header('X-DisputeGuard-Signature'), config('services.disputeguard.webhook_secret'), ); } catch (SignatureVerificationException) { abort(400); } if ($event['type'] === 'dispute.created') { \App\Jobs\HandleNewDispute::dispatch($event['data']['dispute']); } return response()->noContent(); });
Testing your integration
Use Webhook::sign() to produce valid signature headers in your own tests:
$body = json_encode(['id' => 'evt_1', 'type' => 'evidence.requested', 'created_at' => '2026-09-30T12:00:00Z', 'data' => ['dispute' => ['id' => 'd1'], 'order' => ['external_id' => '1042'], 'requested' => []]]); [$status, , $response] = $handler->handle($body, ['X-DisputeGuard-Signature' => Webhook::sign($body, 'whsec_test')]);
Pass a Guzzle MockHandler stack as the handler option to stub API responses.
Development
composer install composer test # vendor/bin/phpunit
License
MIT