Search by

adnane1deev / laravel-charipay

adnane1deev

A Laravel integration for the ChariPay payment API.

Package info

github.com/adnane1deev/laravel-charipay

pkg:composer/adnane1deev/laravel-charipay

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-11-21 08:00 UTC

This package is auto-updated.

Last update: 2026-11-21 08:12:17 UTC


README

A Laravel integration for the ChariPay payment API.

This package provides a simple interface for integrating ChariPay into Laravel applications.

Features

  • Checkout Sessions
  • Refunds
  • Webhook signature verification
  • Webhook event identification
  • Webhook Event Catalogue
  • API authentication
  • Idempotency key support
  • Configurable request timeout
  • API error handling

Requirements

  • PHP 8.1+
  • Laravel 10+

Installation

Install the package using Composer:

composer require adnane1deev/laravel-charipay

Laravel automatically discovers the service provider.

Publish the configuration file:

php artisan vendor:publish --tag=charipay-config

Configuration

Add the following environment variables to your Laravel application's .env file:

CHARIPAY_API_KEY=your_api_key
CHARIPAY_BASE_URL=https://api-psp.charipay.ma
CHARIPAY_TIMEOUT=30
CHARIPAY_WEBHOOK_SECRET=your_webhook_secret
Variable Description Default
CHARIPAY_API_KEY ChariPay API key null
CHARIPAY_BASE_URL ChariPay API base URL https://api-psp.charipay.ma
CHARIPAY_TIMEOUT HTTP request timeout in seconds 30
CHARIPAY_WEBHOOK_SECRET Webhook signing secret null

Keep your API key and webhook secret private. Never commit actual credentials to version control.

Checkout Sessions

The package provides methods to create, retrieve, cancel, and list checkout sessions.

Import the facade:

use Adnane1deev\LaravelCharipay\Facades\Charipay;

Create a Checkout Session

Create a payment session for an order and receive a hosted checkout URL.

$payload = [
    // Required: amount to collect, in MAD (e.g. 149.90 DH).
    'amount' => 149.90,

    // Required: your application's order reference.
    'orderId' => 'ORDER-123',

    // Optional: unique identifier per merchant.
    'externalId' => 'ORDER-123-PAYMENT',

    // Required: checkout configuration.
    'config' => [
        // Required: customer information.
        'customer' => [
            'firstName' => 'Amine',
            'lastName' => 'Bennani',
            'email' => 'amine@example.com',
            'phone' => '+212600000000',
        ],

        // Optional: redirect and webhook notification URLs.
        'urls' => [
            'accept' => 'https://example.com/payment/success',
            'decline' => 'https://example.com/payment/failure',
            'notification' => 'https://example.com/webhooks/charipay',
        ],
    ],

    // Optional: additional information returned in payment webhooks.
    'metadata' => [
        'order_reference' => 'ORDER-123',
        'source' => 'website',
    ],

    // Optional: session expiration (ISO-8601 UTC).
    'expiresAt' => '2026-12-01T12:00:00Z',

    // Optional: receive payment.failed webhook events.
    'notifyOnFailure' => true,

    // Optional: single-use session. Defaults to true.
    'singleUse' => true,
];

$session = Charipay::checkoutSessions()->create(
    payload: $payload,
    idempotencyKey: 'ORDER-123-PAYMENT'
);



use Adnane1deev\LaravelCharipay\Exceptions\ApiException;

try {
    $session = Charipay::checkoutSessions()->create(
        payload: $payload,
        idempotencyKey: 'ORDER-123-PAYMENT'
    );
} catch (ApiException $exception) {
    $exception->getStatusCode();
    $exception->getErrorCode();
    $exception->getCorrelationId();
    $exception->getResponseBody();
}

Request Parameters

Parameter Required Description
amount Yes Payment amount in MAD, major units.
orderId Yes Your order or business reference.
externalId No Unique client-generated identifier per merchant.
config Yes Checkout configuration.
config.customer Yes Customer information.
config.urls No Return and notification URLs.
metadata No Custom data echoed in payment webhooks.
expiresAt No Session expiration in ISO-8601 UTC format.
notifyOnFailure No Enables payment failure notifications.
singleUse No Whether the session can only be paid once.

Important notes:

  • ChariPay uses MAD. Do not include a currency field.
  • orderId and externalId serve different purposes.
  • externalId and the Idempotency-Key header are separate mechanisms.
  • The idempotencyKey argument sets the Idempotency-Key HTTP header.

Response

A successful request returns a response similar to:

{
    "sessionId": "ps_5Kd0Rn",
    "sessionToken": "st_example",
    "verifyKey": "vk_5Kd0Rn",
    "expiresAt": "2026-12-01T12:00:00Z",
    "checkoutUrl": "https://example.com/checkout/ps_5Kd0Rn"
}

Redirect the customer to the returned checkout URL:

return redirect()->away($session['checkoutUrl']);

Payment confirmation: Do not consider the customer returning to your success URL as proof of payment. Confirm successful payments through verified ChariPay webhooks.

The $payload must follow ChariPay's Payment Sessions API requirements.

The idempotency key is optional and helps prevent duplicate session creation when retrying a request.

Retrieve a Checkout Session

$session = Charipay::checkoutSessions()->retrieve(
    'SESSION_ID'
);

Cancel a Checkout Session

$result = Charipay::checkoutSessions()->cancel(
    'SESSION_ID'
);

List Checkout Sessions

$sessions = Charipay::checkoutSessions()->list([
    // ChariPay-supported query parameters
]);

All methods return the decoded API response as an associative PHP array.

Refunds

The package provides methods to create, retrieve, and list refunds.

Import the facade if you haven't already:

use Adnane1deev\LaravelCharipay\Facades\Charipay;

Create a Refund

$refund = Charipay::refunds()->create([
    // Identify the original payment using either operationId or externalId.
    'operationId' => 8123,

    // Your unique reference for this refund.
    'refundReference' => 'refund-ORD-123-1',

    // Required refund reason.
    'reason' => 'CUSTOMER_CANCELLATION',

    // Optional: omit for a full refund.
    'refundAmount' => 100.00,

    // Optional description.
    'note' => 'Customer cancelled the order.',
]);

You must provide refundReference, reason, and either operationId or externalId.

The refundReference also acts as the idempotency reference. Reusing the same reference prevents the same refund from being processed twice.

A newly created refund returns 202 Accepted while it is being processed. Follow its final status through webhooks rather than assuming the refund has completed immediately.

Retrieve a Refund

$refund = Charipay::refunds()->retrieve(
    'refund-ORD-123-1'
);

You can retrieve a refund using your refundReference or the refund ID assigned by ChariPay.

List Refunds

$refunds = Charipay::refunds()->list([
    'status' => 'SUCCESS',

    // Add ChariPay-supported pageable parameters here.
]);

You can optionally filter refunds by status: PENDING, SUCCESS, or FAILED.

All methods return the decoded API response as an associative PHP array.

Webhooks

The package provides helpers for verifying webhook signatures and extracting webhook information.

Verify a Webhook Signature

Always verify the signature before processing a webhook payload.

use Illuminate\Http\Request;
use Adnane1deev\LaravelCharipay\Facades\Charipay;

Route::post('/webhooks/charipay', function (Request $request) {
    if (! Charipay::webhooks()->verify($request)) {
        return response()->json([
            'message' => 'Invalid webhook signature.',
        ], 401);
    }

    $payload = Charipay::webhooks()->payload($request);
    $eventType = Charipay::webhooks()->eventType($request);
    $eventId = Charipay::webhooks()->eventId($request);

    switch ($eventType) {
        case 'YOUR_PAYMENT_SUCCESS_EVENT':
            // Example: mark the related order as paid.
            // $orderService->markAsPaid($payload);

            break;

        case 'YOUR_PAYMENT_FAILURE_EVENT':
            // Example: mark the related order as payment failed.
            // $orderService->markAsPaymentFailed($payload);

            break;

        default:
            // Log events your application does not handle.
            logger()->info('Unhandled ChariPay webhook event.', [
                'event_type' => $eventType,
                'event_id' => $eventId,
            ]);

            break;
    }

    return response()->json(['received' => true]);
});

Extract Webhook Information

The package provides methods to retrieve webhook identifiers and event information:

$eventId = Charipay::webhooks()->eventId($request);

$eventType = Charipay::webhooks()->eventType($request);

$deliveryId = Charipay::webhooks()->deliveryId($request);

$payload = Charipay::webhooks()->payload($request);
  • eventId() returns the stable event identifier.
  • eventType() returns the event type.
  • deliveryId() returns the individual delivery identifier.
  • payload() returns the decoded JSON payload as an associative array.

Prevent Duplicate Processing

ChariPay may deliver the same event more than once.

Use eventId() as your deduplication key. Store processed event IDs in your application's database and ensure that checking the ID, processing the event, and recording completion are handled safely.

Do not use the delivery ID as the deduplication key.

Important

  • Always verify webhook signatures before processing payloads.
  • Keep your webhook secret private.
  • Return a successful HTTP response only after the event has been safely processed or recorded for reliable background processing.
  • Handle duplicate deliveries gracefully.

Event Catalogue

The package allows you to retrieve ChariPay's webhook event catalogue.

List All Event Types

$events = Charipay::events()->list();

List Emitted Event Types Only

$events = Charipay::events()->list(
    emittedOnly: true
);

Set emittedOnly to true to filter the catalogue to event types that ChariPay emits.

Exception Handling

The package provides two exception classes:

  • CharipayException: Base exception for package-level errors.
  • ApiException: Exception thrown when ChariPay returns an unsuccessful HTTP response.

Catch API Exceptions

use Adnane1deev\LaravelCharipay\Exceptions\ApiException;

try {
    $session = Charipay::checkoutSessions()->create($payload);
} catch (ApiException $exception) {
    $statusCode = $exception->getStatusCode();
    $responseBody = $exception->getResponseBody();

    logger()->error('ChariPay API request failed.', [
        'status' => $statusCode,
        'response' => $responseBody,
    ]);
}

Catch General Package Exceptions

use Adnane1deev\LaravelCharipay\Exceptions\CharipayException;

try {
    $session = Charipay::checkoutSessions()->create($payload);
} catch (CharipayException $exception) {
    logger()->error('ChariPay package error.', [
        'message' => $exception->getMessage(),
    ]);
}

ApiException extends CharipayException, so catching the base exception also catches API exceptions.

ChariPay Documentation

For API endpoint details, request parameters, response formats, and webhook configuration, refer to the official documentation:

License

This package is open-source software licensed under the MIT License.