DEV Community

Michael Smith for Blocksreader

Posted on Edited on Originally published at blocksreader.com

Accept crypto payments in Laravel (USDT, BTC, ETH)

This guide adds crypto deposits to a Laravel app: every user gets their own address, your app is told when money arrives, and the user's balance goes up exactly once. It uses the BlocksReader API and runs entirely in test mode, so you can build it today without real funds.

Prefer to start from working code? Our Laravel starter project does everything below, with tests.

1. Configuration

Get a free test key (br_test_...) from the dashboard and add it to .env with your webhook secret (you'll get it in step 4):

BLOCKSREADER_API_KEY=br_test_...
BLOCKSREADER_WEBHOOK_SECRET=whsec_...
Enter fullscreen mode Exit fullscreen mode
// config/services.php
'blocksreader' => [
    'key' => env('BLOCKSREADER_API_KEY'),
    'webhook_secret' => env('BLOCKSREADER_WEBHOOK_SECRET'),
],
Enter fullscreen mode Exit fullscreen mode

Keep the key on the server. It must never reach a browser or a mobile app.

2. Tables

Schema::create('deposit_addresses', function (Blueprint $t) {
    $t->id();
    $t->foreignId('user_id')->constrained();
    $t->string('chain');
    $t->string('address_id')->unique();
    $t->string('address');
    $t->timestamps();
    $t->unique(['user_id', 'chain']);
});

Schema::create('crypto_deposits', function (Blueprint $t) {
    $t->id();
    $t->foreignId('user_id')->constrained();
    $t->string('chain');
    $t->string('tx_hash');
    $t->string('address');
    $t->string('asset');
    $t->decimal('amount', 38, 18);
    $t->timestamps();
    $t->unique(['chain', 'tx_hash', 'address']); // credit exactly once
});
Enter fullscreen mode Exit fullscreen mode

3. Give each user an address

use Illuminate\Support\Facades\Http;

function depositAddressFor(User $user, string $chain): DepositAddress
{
    return DepositAddress::where(['user_id' => $user->id, 'chain' => $chain])->firstOr(function () use ($user, $chain) {
        $res = Http::withToken(config('services.blocksreader.key'))
            ->withHeaders(['Idempotency-Key' => "address-user-{$user->id}-{$chain}"])
            ->post('https://api.blocksreader.com/v1/addresses', [
                'chain' => $chain,          // tron, bsc, ethereum, bitcoin...
                'ref'   => "user_{$user->id}",
            ])->throw()->json('data');

        return DepositAddress::create([
            'user_id' => $user->id, 'chain' => $chain,
            'address_id' => $res['id'], 'address' => $res['address'],
        ]);
    });
}
Enter fullscreen mode Exit fullscreen mode

Call it when the user opens your deposit page, and show the address with a QR code. ref comes back on every deposit, so you always know whose money it is.

4. Register the webhook

curl https://api.blocksreader.com/v1/webhooks \
  -H "Authorization: Bearer $BLOCKSREADER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://your-app.com/api/webhooks/blocksreader", "events": ["deposit.confirmed"] }'
Enter fullscreen mode Exit fullscreen mode

Copy the secret from the response into BLOCKSREADER_WEBHOOK_SECRET. While developing locally, cloudflared tunnel --url http://localhost:8000 gives you a public https URL.

5. Handle the webhook

Add the route to routes/api.php. API routes skip CSRF, and Laravel adds /api to the front of their URLs, which is why step 4 registers /api/webhooks/blocksreader. On Laravel 11 or newer, run php artisan install:api first if you don't have that file.

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/blocksreader', function (Illuminate\Http\Request $request) {
    parse_str(str_replace(',', '&', (string) $request->header('BR-Webhook-Signature')), $p);
    $t = (int) ($p['t'] ?? 0);
    abort_if(abs(time() - $t) > 300, 401);
    $expected = hash_hmac('sha256', $t . '.' . $request->getContent(), config('services.blocksreader.webhook_secret'));
    abort_unless(hash_equals($expected, (string) ($p['v1'] ?? '')), 401);

    $event = json_decode($request->getContent(), true);
    if ($event['type'] === 'deposit.confirmed') {
        $d = $event['data'];
        $userId = (int) str_replace('user_', '', $d['ref'] ?? '');
        if (! User::whereKey($userId)->exists()) {
            Log::critical('Deposit without a matching user', ['tx_hash' => $d['tx_hash'], 'ref' => $d['ref'] ?? null]);
            abort(422); // not credited: the webhook is retried while you look into it
        }
        DB::transaction(function () use ($d, $userId) {
            $inserted = DB::table('crypto_deposits')->insertOrIgnore([
                'user_id' => $userId, 'chain' => $d['chain'], 'tx_hash' => $d['tx_hash'],
                'address' => $d['address'], 'asset' => $d['asset'], 'amount' => $d['amount'],
                'created_at' => now(), 'updated_at' => now(),
            ]);
            if ($inserted) {
                // credit $d['amount'] of $d['asset'] to $userId here
            }
        });
    }
    return response()->noContent(200);
});
Enter fullscreen mode Exit fullscreen mode

The user check matters: on MySQL, insertOrIgnore also hides foreign key errors, so without it a deposit for an unknown user would disappear silently.

Every deposit is announced twice (at 1 and 3 confirmations). insertOrIgnore on the unique key turns the second one into a no-op, so the user is credited once. For tokens, asset is the contract address; map it to a symbol with GET /v1/assets?chain=... or keep a small lookup table.

6. Test it

curl https://api.blocksreader.com/v1/sandbox/deposits \
  -H "Authorization: Bearer $BLOCKSREADER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "address_id": "adr_...", "amount": "25", "asset": "USDT" }'
Enter fullscreen mode Exit fullscreen mode

Your route receives the webhook about 5 seconds later, and again 6 seconds after that. Check crypto_deposits has one row and the balance went up once.

7. Catch-up job

Schedule a command every five minutes that pages through GET /v1/deposits?status=confirmed (newest first), goes back a fixed window such as the last 48 hours, and credits anything new through the same code. Don't stop at the first deposit you already credited: an older one may still be missing. It covers deploys and downtime when a webhook can't reach you.

// routes/console.php
use Illuminate\Support\Facades\Schedule;

Schedule::command('deposits:catch-up')->everyFiveMinutes();
Enter fullscreen mode Exit fullscreen mode

Going live

Run the BlocksReader Signer with Docker on a server you control (it creates your wallet, and the keys stay with you), choose a plan, and swap in your br_live_ key.


Originally published at blocksreader.com/guides/accept-crypto-payments-laravel. You can try everything in this guide for free in the BlocksReader sandbox.

Top comments (0)