Docs
Checking Raims account
Integrations

PHP SDK

Install the official SDK through Composer and connect your PHP backend to the Raims public API.

Use the raims/raims-php package to integrate a server application written in PHP with the public API. The SDK organizes resources into services, with typed responses, cursor pagination, and webhook signature verification.

Keep the API key in the integration backend. Do not distribute credentials in code delivered to a browser or in your customers' applications.

Install the package

The SDK requires PHP 8.2 or later on a 64-bit platform, Composer 2, and the curl, json, and hash extensions. From your application directory:

Shell
composer require raims/raims-php

The package is available on Packagist. Without a version argument, Composer installs the latest stable version compatible with the project and records the constraint in composer.json. Keep your application's composer.lock to repeat installation of the same version. Check extensions and platform requirements with composer check-platform-reqs after installing. The SDK does not require third-party production libraries.

Configure the client

  1. Prepare the credential

    Obtain a key through API keys and store it in a protected environment variable or your application's secret store. The validated credential determines the company, environment, and permissions in the API. Sandbox and Production use https://api.raims.com.

    For this first read, use a Sandbox key with View customers permission. The request only reads one page; it does not create customers or request emails.

  2. Save the read example

    read-customers.php
    PHP
    <?php
    
    require __DIR__ . '/vendor/autoload.php';
    
    use Raims\Exception\ApiErrorException;
    use Raims\RaimsClient;
    
    $apiKey = getenv('RAIMS_API_KEY');
    if ($apiKey === false || $apiKey === '') {
        throw new RuntimeException('Set RAIMS_API_KEY on the server.');
    }
    
    $raims = new RaimsClient($apiKey);
    try {
        $customers = $raims->customers->all(['page_size' => 10]);
        printf("HTTP status: %d; items: %d\n", $customers->getLastResponse()->statusCode, count($customers));
    } catch (ApiErrorException $error) {
        fprintf(STDERR, "HTTP status: %s; code: %s; Request-Id: %s\n",
            $error->getHttpStatus(), $error->getErrorCode(), $error->getRequestId());
        exit(1);
    }
  3. Run and check the result

    From the project directory, with RAIMS_API_KEY available to the process, run:

    Shell
    php read-customers.php

    A successful read prints HTTP status: 200 and the number of items in this page. items: 0 is a valid empty result for the key’s company and environment. It is not an authentication failure.

What to check

The SDK reads the list and page envelope below. In an empty page, has_next: false means there is no next page. A nonempty page also returns customer records; the program prints only their count.

HTTP 200 response example excerptGET /v1/customers

No customers found

JSON
{
  "list": [],
  "page": {
    "page_size": 10,
    "has_next": false,
    "has_previous": false,
    "next_after": null,
    "previous_before": null
  }
}

Reuse the instance to benefit from HTTP connections. The following snippets assume that the application has configured $raims.

Create a customer and a charge

This is a backend snippet, after loading the order from your application’s storage. Keep the customer key separate from the charge key. Save the entire request payload, including the amount and title, before sending; read it again on retries instead of generating new values.

Input from the saved orderSource and purpose
$customerTaxIdCustomer tax ID already authorized and saved by your application.
$customerIdempotencyKeyIdempotency key for creating this customer; saved before the first request.
$chargeIdempotencyKeyA different idempotency key for this charge; saved with the order.
$chargeDueDateChosen due date, saved in UTC Unix seconds.
PHP
$customer = $raims->customers->create([
    'tax_id' => $customerTaxId,
], [
    'idempotency_key' => $customerIdempotencyKey,
]);

$charge = $raims->charges->create([
    'customer_id' => $customer->id,
    'amount_cents' => 15000,
    'due_date' => $chargeDueDate,
    'title' => 'Pedido 1234',
], [
    'idempotency_key' => $chargeIdempotencyKey,
]);

$chargeId = $charge->id;
$httpStatus = $charge->getLastResponse()->statusCode;
$requestId = $charge->getLastResponse()->getRequestId();
$pending = $httpStatus === 202;

Persist the returned customer ID and charge ID on the order before returning success to your caller. The charge ID is the value used to resume the read below; the SDK variables are not durable storage.

ResultWhat to do next
HTTP 201The charge was created. Save its ID; creation does not confirm payment. This snippet does not request email or payment issuance.
HTTP 202 in a creation that requests payment issuanceSave the same returned ID and keep the order pending. Retrieve that charge; do not create another one to resolve the pending result.
Error or missing responseHandle the structured error. If execution is uncertain, keep the intent and reconcile before retrying with the original key and payload.

The canonical creation example below shows only the ID and status fields:

HTTP 201 response example excerptPOST /v1/charges

Charge without a link or email request

JSON
{
  "id": "ch_1Q2W3E4R5T6Y7U8I9O0P",
  "status": 0
}

If the CPF or CNPJ already exists within the same company and environment, the customer is updated and keeps its identifier. 15000 represents BRL 150.00. See the fields and conditions in Create charge. When repeating the same intent after losing a response, keep the key and every parameter, including the due date. An order's external reference does not replace idempotency.

Pagination and pending results

The following backend snippet counts at most 100 customers across pages, without logging their records. Keep the configured client open during iteration.

PHP
$visited = 0;
$page = $raims->customers->all(['page_size' => 50]);
foreach ($page->autoPagingIterator() as $customer) {
    $visited++;
    if ($visited === 100) break;
}
printf("Items visited: %d\n", $visited);

Items visited: 0 means the query found no customers. 100 means the chosen limit was reached; it does not prove there are no more records. A page error interrupts the count. Save progress only after processing a complete page if your job must resume later.

all() fetches one page. Enumerating that page does not send further requests. Use nextPage() and previousPage() to navigate; the SDK preserves filters and returns null when no page exists in the selected direction.

autoPagingIterator() loads subsequent pages during enumeration and can send multiple requests. Leaving the foreach stops further fetches. Copy the returned cursors and keep the filters; do not send after and before together. See Listing and pagination.

HTTP 202 keeps the result pending. It does not confirm payment and the SDK does not start polling. When resuming the saved order, load $chargeId from storage and retrieve that same charge once:

PHP
$current = $raims->charges->retrieve($chargeId);
printf("HTTP status: %d; charge status: %d\n",
    $current->getLastResponse()->statusCode, $current->status);

HTTP 200 here confirms that the read succeeded. Interpret the returned status and payment_information using the charge reference; a successful GET does not mean the charge was paid or that issuance completed. If issuance is still pending, keep the same ID. Repeated reads do not speed up processing or issue another payment; contact support if the condition persists.

Idempotency and errors

Pass idempotency_key in request options only for endpoints that accept Idempotency-Key. The SDK does not generate keys or automatically retry POST, PATCH, or DELETE. Read retries are optional; the default is zero.

Handle HTTP failures through ApiErrorException, using getHttpStatus() and getErrorCode(). getRequestId() helps identify the attempt. The text in error.message is a human diagnostic and must not be compared as a control code. Do not log complete responses, credentials, personal documents, or temporary links. See Idempotency and the SDK error guide.

In updates, omitting a field preserves its value. Sending null clears only fields whose contract permits that action. Use (object) [] for an empty object in an input; an empty PHP array represents a list. Check each endpoint's conditions.

For example, if the read above returns HTTP 403 with API_KEY_PERMISSION_DENIED, the key lacks access to list customers. Enable View customers on the appropriate key and retry the read. Repeating it with the same permissions will not resolve that error.

For field validation failures, use error.details[].field and error.details[].code to locate the input to correct. Check HTTP response codes for other failures.

For an uncertain write, recover the saved key and the entire original payload. If the charge ID was received, retrieve that ID first. Within the idempotency retention period, a compatible retry can return the preserved result, including a pending 202. A key with different parameters can be rejected; do not change the due date or create a new key to bypass the uncertainty. After retention expires, reconcile before another write.

Use Sandbox

Use a Sandbox key for simulations in $raims->simulations->charges and $raims->simulations->refunds. A Production key does not become a Sandbox key when these services are used. See the rules and conditions in the Simulations reference.

Requests that ask for email or webhook deliveries can reach external destinations even in Sandbox. Use only destinations authorized for your integration.

Receive webhooks

Read the original body and the headers received by your server:

PHP
use Raims\Exception\SignatureVerificationException;
use Raims\Webhook;

$payload = file_get_contents('php://input');
if ($payload === false) {
    throw new RuntimeException('Unable to read the request body.');
}

$headers = [
    'webhook-id' => $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    'webhook-timestamp' => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    'webhook-signature' => $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
];

try {
    $event = Webhook::constructEvent($payload, $headers, $webhookSecret);
} catch (SignatureVerificationException $error) {
    http_response_code(400);
    exit;
}

This snippet ends after authentication. Your handler still needs to implement the following contract; constructEvent does not save or deduplicate events.

Handler resultHTTP response
Invalid signature400, as in the catch above; no processing.
Valid signature, authorized type and environment, and event stored durably (or already accepted by ID)204; the same event must not repeat its effect.
Persistence failed5xx; do not acknowledge success before the work is durable.

$webhookSecret is the secret_key returned when creating or rotating a webhook, not the API Bearer key. Preserve the original body bytes and do not reserialize the JSON before authentication. A failure raises SignatureVerificationException; do not process the body in that case.

A valid signature does not eliminate duplicates. Check type and environment, deduplicate by the event id, and store the work durably before responding with success. The webhook-id header identifies the delivery and does not replace the event identifier. See Receive events.

Update the SDK

To get the latest stable version, run the command again without a version argument:

Shell
composer require raims/raims-php

Composer chooses a constraint based on the available versions and updates composer.json and composer.lock. Check the releases and test the flows used by your integration. The SDK version is independent of the API HTTP version /v1.

Full guides and the service reference are available in the SDK repository.