EthioDeploy
DocsPricingDomainsBlogToolsChangelog

Blog/Tutorials

Accept Chapa payments in Laravel

BS
Brook SolomonPublished November 15, 2026
Share on XShare on LinkedIn
Http::withToken(...)->post(...)

THE SHORT ANSWER

To take Chapa payments in Laravel, save a pending order with a unique tx_ref, POST it to https://api.chapa.co/v1/transaction/initialize with Laravel's HTTP client and your secret key, and redirect the customer to the checkout_url Chapa returns. Mark the order paid only after GET /v1/transaction/verify/<tx_ref> reports success with the amount, currency and mode you expect. Run that check from all three places Chapa can reach you: the GET to your callback_url, the customer's redirect to your return_url, and the webhook POST, which you exclude from Laravel's CSRF middleware.

Should I use the chapa-laravel package?

Chapa's SDK page links a Laravel package, chapa/chapa-laravel, and says some of the listed SDKs come from its developer community rather than Chapa. As of November 2026, its latest tagged release on Packagist is 1.0.2 from July 2024, which only allows illuminate/support up to Laravel 10. The main branch allows up to Laravel 12. Laravel 13 is the current release, so on a new app composer require chapa/chapa-laravel won't install.

You don't need it. Chapa's API is two calls, initialize and verify, and Laravel's Http facade does both in a few lines. The code below targets Laravel 13 and works on 11 and 12 with one change, noted where it comes up.

Where do the keys go?

Copy the test secret key from the Chapa dashboard (test keys have TEST in their prefix, and no real money moves in test mode) and add it to .env:

CHAPA_SECRET_KEY=CHASECK_TEST-xxxxxxxxxxxxxxxx
CHAPA_WEBHOOK_SECRET=a-long-random-string

Then read them through a config file, not with env() in your code:

// config/services.php
'chapa' => [
    'secret_key' => env('CHAPA_SECRET_KEY'),
    'webhook_secret' => env('CHAPA_WEBHOOK_SECRET'),
],

Laravel's docs explain why: once php artisan config:cache has run, “the .env file will not be loaded; therefore, the env function will only return external, system level environment variables.” Production deploys usually cache config, so config('services.chapa.secret_key') is the call that keeps working everywhere.

What do I store for each payment?

One row per attempt, keyed by tx_ref. Chapa rejects a reused reference with a 400, “Transaction reference has been used before”, so generate a new one each time:

// database/migrations/xxxx_create_orders_table.php
Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->string('tx_ref')->unique();
    $table->decimal('amount', 12, 2);
    $table->string('currency', 3)->default('ETB');
    $table->string('email');
    $table->string('status')->default('pending');
    $table->timestamps();
});
// app/Models/Order.php
class Order extends Model
{
    protected $fillable = ['tx_ref', 'amount', 'currency', 'email', 'status'];
}

How do I initialize and verify a payment?

Put both API calls in one small class so every route uses the same checks:

// app/Services/Chapa.php
namespace App\Services;

use App\Models\Order;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class Chapa
{
    private const BASE = 'https://api.chapa.co/v1';

    public function initialize(Order $order, string $callbackUrl, string $returnUrl): string
    {
        $response = Http::withToken(config('services.chapa.secret_key'))
            ->acceptJson()
            ->post(self::BASE.'/transaction/initialize', [
                'amount' => (string) $order->amount,
                'currency' => $order->currency,
                'email' => $order->email,
                'tx_ref' => $order->tx_ref,
                'callback_url' => $callbackUrl,
                'return_url' => $returnUrl,
                'customization' => ['title' => 'My Shop', 'description' => 'Order payment'],
            ]);

        if ($response->json('status') !== 'success') {
            throw new RuntimeException('Chapa initialize failed: '.json_encode($response->json('message')));
        }

        return $response->json('data.checkout_url');
    }

    public function verify(Order $order): bool
    {
        $response = Http::withToken(config('services.chapa.secret_key'))
            ->acceptJson()
            ->get(self::BASE.'/transaction/verify/'.rawurlencode($order->tx_ref));

        if (! $response->successful()) {
            return false; // 404 means "Payment not paid yet"
        }

        $data = $response->json('data') ?? [];
        $mode = str_contains((string) config('services.chapa.secret_key'), 'TEST') ? 'test' : 'live';

        return ($data['status'] ?? null) === 'success'
            && ($data['tx_ref'] ?? null) === $order->tx_ref
            && ($data['currency'] ?? null) === $order->currency
            && round((float) ($data['amount'] ?? 0), 2) === round((float) $order->amount, 2)
            && ($data['mode'] ?? null) === $mode;
    }

    // Safe to call from the callback, the return page and the webhook at once.
    public function markPaidIfVerified(Order $order): bool
    {
        if ($order->status === 'paid') {
            return true;
        }
        if (! $this->verify($order)) {
            return false;
        }

        $changed = Order::where('tx_ref', $order->tx_ref)
            ->where('status', 'pending')
            ->update(['status' => 'paid']);

        if ($changed === 1) {
            // Only the first caller gets here: send the receipt, ship the goods.
        }

        return true;
    }
}

A few details that matter:

  • currency is ETB or USD. If you add phone_number, Chapa wants 10 digits.
  • The amount is compared as a number because Chapa's examples show it as a number in the verify response and as a string like "400.00" in webhooks.
  • status can be success, pending or failed. Only success means paid.
  • The update() with where('status', 'pending') returns the number of rows it changed, so when the callback and the webhook land together, only one of them sees 1 and fulfils the order.

Which routes do I need?

Four: start the checkout, Chapa's callback, the customer's return page and the webhook.

// routes/web.php
use App\Http\Controllers\ChapaController;

Route::post('/checkout', [ChapaController::class, 'checkout'])->name('checkout');
Route::get('/chapa/callback', [ChapaController::class, 'callback'])->name('chapa.callback');
Route::get('/orders/{txRef}', [ChapaController::class, 'show'])->name('orders.show');
Route::post('/chapa/webhook', [ChapaController::class, 'webhook'])->name('chapa.webhook');
// app/Http/Controllers/ChapaController.php
namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\Chapa;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class ChapaController extends Controller
{
    public function checkout(Request $request, Chapa $chapa)
    {
        $data = $request->validate(['email' => ['required', 'email']]);

        $order = Order::create([
            'tx_ref' => 'order-'.Str::uuid(),
            'amount' => '500.00', // from your database, never from the form
            'currency' => 'ETB',
            'email' => $data['email'],
        ]);

        $checkoutUrl = $chapa->initialize(
            $order,
            route('chapa.callback'),
            route('orders.show', $order->tx_ref),
        );

        return redirect()->away($checkoutUrl);
    }

    public function callback(Request $request, Chapa $chapa)
    {
        $txRef = $request->query('trx_ref') ?? $request->query('tx_ref');
        abort_unless($txRef, 400, 'missing trx_ref');

        if ($order = Order::where('tx_ref', $txRef)->first()) {
            $chapa->markPaidIfVerified($order);
        }

        return response('ok');
    }

    public function show(string $txRef, Chapa $chapa)
    {
        $order = Order::where('tx_ref', $txRef)->firstOrFail();

        return view('orders.show', [
            'order' => $order,
            'paid' => $chapa->markPaidIfVerified($order),
        ]);
    }

    public function webhook(Request $request, Chapa $chapa)
    {
        $signature = $request->header('x-chapa-signature') ?? $request->header('chapa-signature');
        $expected = hash_hmac('sha256', $request->getContent(), (string) config('services.chapa.webhook_secret'));
        if (! $signature || ! hash_equals($expected, $signature)) {
            Log::warning('Chapa webhook signature mismatch', ['tx_ref' => $request->input('tx_ref')]);
        }

        if ($request->input('event') === 'charge.success'
            && $order = Order::where('tx_ref', $request->input('tx_ref'))->first()) {
            $chapa->markPaidIfVerified($order);
        }

        return response('ok');
    }
}

The form that starts it is a normal Blade form with @csrf posting an email field to {{ route('checkout') }}. redirect()->away() is Laravel's redirect for an external URL, which Chapa's checkout page is.

What's the difference between callback_url and return_url?

callback_url is for your server. Chapa's docs say it receives a GET with trx_ref, ref_id and status, and should be a script that uses the verify endpoint. Note the spelling: trx_ref, not tx_ref. The controller reads both in case that changes.

return_url is for the customer: Chapa redirects their browser there after paying. The page verifies too, because the customer can arrive before the callback has run. Neither request proves anything by itself. A status=success in the query string is just text in a URL; the verify call is the proof.

How do I set up the Chapa webhook in Laravel?

In the Chapa dashboard, open your profile settings, then the Webhooks tab, and add your URL and a secret. Chapa POSTs JSON with an event such as charge.success, charge.failed or charge.refunded, and the tx_ref. Without a 200 response, its docs say it keeps sending the event every 10 minutes, for up to 10 attempts.

Laravel's CSRF middleware rejects a POST from another site that has no CSRF token, and Chapa can't send one, so exclude the route. In Laravel 13, in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        'chapa/webhook',
    ]);
})

On Laravel 11 and 12 the method is validateCsrfTokens(except: [...]). Laravel 13 renamed the middleware from VerifyCsrfToken to PreventRequestForgery and added preventRequestForgery(). Without the exclusion, every webhook gets a 419 and Chapa keeps retrying.

The controller logs a bad signature instead of rejecting it, for the same reason as in our Next.js version: Chapa's webhook page describes x-chapa-signature as an HMAC SHA256 of the payload signed with your secret key, calls the dashboard value a “secret hash”, and describes chapa-signature differently. Its Node example hashes JSON.stringify of the parsed body, which only equals the raw body if Chapa sends compact JSON. Send a test event, see which header and secret match, then return a 401 on mismatch. Orders stay safe either way, because the webhook only triggers a verify call and verify answers from Chapa's records.

How do I test it?

With test keys, Chapa accepts only its test cards and phone numbers; any other number returns failed.

MethodTest numberAlso enter
Card4200 0000 0000 0000 or 5400 0000 0000 0000CVV 123, expiry 12/34
telebirr, CBE Birr, COOPPay-ebirr0900123456, 0900112233, 0900881111No OTP listed
Awash Bank, Amole0900123456, 0900112233, 0900881111OTP 12345
M-Pesa0700123456, 0700112233, 0700881111None listed

Chapa can't reach localhost, so locally you can test the checkout redirect and the return page. Test the callback and the webhook on the deployed app.

How do I deploy it on EthioDeploy?

Push the repo to GitHub and create a project from it. Laravel is detected from artisan and runs on nginx and PHP-FPM; the Laravel deploy guide has the details. For Chapa specifically:

  1. Add trustProxies(at: '*') in bootstrap/app.php, next to the CSRF exclusion. HTTPS ends at the platform's proxy, and route() builds URLs from the incoming request, so without it the callback_url and return_url you send Chapa start with http://.
  2. Add CHAPA_SECRET_KEY, CHAPA_WEBHOOK_SECRET, APP_URL and the usual APP_ENV=production in the project's environment variables. Config is cached when the container starts, so change a key and redeploy.
  3. Add a MySQL or Postgres addon and set DB_CONNECTION. New Laravel apps default to SQLite, and that file is wiped on every deploy, orders included. Set the Start command to php artisan migrate --force && ethiodeploy-start so the orders table exists.
  4. Set the webhook URL in the Chapa dashboard to https://<project-slug>.ethiodeploy.app/chapa/webhook, make a test payment, and look for the signature warning in the Logs tab.
  5. Switch to live keys once the whole flow works.

On the Free plan the app sleeps after 30 minutes without traffic. A callback or webhook that arrives while it sleeps wakes it, and the request waits up to 30 seconds. If Chapa gives up first, the webhook retries 10 minutes later and the return page verifies on its own, so the payment is delayed, not lost. A shop taking real orders belongs on Pro, which never sleeps and can be paid in Birr.

Questions

Chapa's SDK page links chapa/chapa-laravel, but notes that some listed SDKs are community-made. Its latest tagged release (1.0.2, July 2024) supports Laravel up to 10, and the main branch up to 12, so on Laravel 13 the HTTP client is the simpler route.

Laravel's CSRF middleware rejects the POST because Chapa sends no CSRF token. Exclude the route with preventRequestForgery(except: [...]) in Laravel 13, or validateCsrfTokens(except: [...]) in Laravel 11 and 12.

The key isn't in the environment the cached config was built from. Add it to .env locally or to the host's environment variables, then rebuild the config cache (on EthioDeploy, redeploy).

Yes. Pass currency USD instead of ETB to initialize. Chapa accepts ETB and USD.

Check that the key and transaction are in the same mode: a live key can't verify a test transaction or the other way round. Also check the amount and currency you stored match what you sent to initialize.

Sources

Checked on November 15, 2026:

  • Chapa: Accept payments
  • Chapa: Verify payments
  • Chapa: Webhooks
  • Chapa: Test mode vs live mode
  • Chapa: Testing cards
  • Chapa: Testing mobile numbers
  • Chapa: SDKs and plugins
  • chapa/chapa-laravel on Packagist
  • Laravel 13: CSRF protection
  • Laravel 13: HTTP client
  • Laravel 13: Configuration caching
  • Laravel 13: Upgrade guide
  • Laravel 13: Trusting proxies

Push a repo. Get a URL.

  • Deploy a Laravel app
  • Web hosting in Ethiopia
  • Database addons
  • Environment variables
Start free

Join the EthioDeploy Telegram

Release notes as they ship, plus deploy help from the team and other developers.

Join on Telegram
BS
WRITTEN BYBrook SolomonFounder, EthioDeploy

Brook Solomon founded EthioDeploy and builds its deploy pipeline, build servers and AI coding agent. The posts here come from errors seen in real deploys on the platform.

All posts by Brook →
On this page
  • Should I use the chapa-laravel package?
  • Where do the keys go?
  • What do I store for each payment?
  • How do I initialize and verify a payment?
  • Which routes do I need?
  • What's the difference between callback_url and return_url?
  • How do I set up the Chapa webhook in Laravel?
  • How do I test it?
  • How do I deploy it on EthioDeploy?
  • Questions
  • Sources
0% read

Keep reading

  • POST /v1/transaction/initialize

    TutorialsNov 4, 2026

    Accept Chapa payments in Next.js and deploy it

    To take Chapa payments in Next.js, call Chapa's initialize endpoint from the server with your secret key, redirect the customer to the checkout_url it returns, and mark the order paid only after GET /v1/transaction/verify/<tx_ref> says the status is success and the amount, currency and mode match. Chapa tells you a payment happened three ways: the customer comes back to your return_url, Chapa calls your callback_url, and it POSTs a webhook. Treat all three as a cue to verify, never as proof.

  • 53300

    Fix deploy errorsNov 17, 2026

    Postgres "too many connections" after deploy: how to fix it

    Postgres refuses new connections with "FATAL: sorry, too many clients already" (SQLSTATE 53300, too_many_connections) once every slot under max_connections is taken, and max_connections defaults to 100. After a deploy the usual cause is arithmetic: each process of your app opens its own pool (10 for node-postgres and Prisma 7, 15 for SQLAlchemy), you run several processes, and for a short time the old and the new copy of the app are both connected. Count connections in pg_stat_activity, make copies × processes × pool max fit under the limit with room to spare, release clients you check out, set idle_in_transaction_session_timeout, and put PgBouncer in front when the numbers can't fit.

  • NEXT_PUBLIC_*

    Fix deploy errorsNov 17, 2026

    NEXT_PUBLIC_ env variables undefined in production: causes and fixes

    A NEXT_PUBLIC_ variable is undefined in production when it wasn't set while next build ran. Next.js replaces every process.env.NEXT_PUBLIC_ reference with a fixed value during the build, so a variable added to the server afterwards changes nothing until you build again. The other usual causes are reading it dynamically (process.env[name] or a copy of process.env), a name without the NEXT_PUBLIC_ prefix in a Client Component, and one Docker image promoted across environments. For values that must change without a rebuild, read them on the server at request time and pass them down.

EthioDeploy

Agentic first development and deployment, started in Ethiopia, built for developers everywhere.

Telegram community
Product
PricingAI coding agentAgent mode docsDomainsCLIFree backend hostingHosting in EthiopiaChangelog
Deploy guides
Next.jsNode.jsPythonSvelteKitTanStack StartAstroNuxtReact RouterHonoStrapiDjangoFastAPIFlaskStreamlitExpressNestJSLaravelRailsGoTelegram botDiscord botLovableBoltReplitv0Google AI StudioBase44Firebase StudioClaude Code & Cursor
Compare
vs Herokuvs Vercelvs Rendervs Railwayvs Fly.iovs Netlifyvs KoyebHeroku alternativesVercel alternativesNetlify alternativesRender alternativesRailway alternativesFly.io alternativesReplit alternativesPythonAnywhere alternativesDigitalOcean App Platform alternativesGlitch alternatives
Resources
DocsBlogFree toolsAboutSupportContactllms.txt
© 2026 EthioDeployPay by card in USD or bank transfer in ETBTermsPrivacy