Skip to content

SDKs

PHP SDK (Laravel)

Create payments, check their status and verify webhooks from any PHP 8.1+ backend: Laravel, Symfony, CodeIgniter or plain PHP. This page also has a complete Laravel integration for a mobile app (Flutter, Android or React Native).

1. Install

Shell
composer require worldxgrowth/razcrypto-php-sdk

From the download (local / no Packagist)

Shell
# from your project root
mkdir -p packages
curl -L -o razcrypto-php-sdk.zip https://razcryptogateway.com/downloads/razcrypto-php-sdk.zip
unzip razcrypto-php-sdk.zip -d packages      # creates packages/razcrypto-php-sdk

Tell Composer about the local folder, then require it:

JSON
{
  "repositories": [{ "type": "path", "url": "packages/razcrypto-php-sdk" }],
  "require": { "worldxgrowth/razcrypto-php-sdk": "*" }
}
Shell
composer update worldxgrowth/razcrypto-php-sdk

No Composer at all? Register a PSR-4 autoloader for the RazCrypto\ namespace that points at packages/razcrypto-php-sdk/src/.

From GitHub (development)

JSON
{
  "repositories": [{ "type": "vcs", "url": "https://github.com/WorldxGrowth/razcrypto-php-sdk" }],
  "require": { "worldxgrowth/razcrypto-php-sdk": "dev-main" }
}

2. Keys

Put the keys in .env, never in code or in the app:

Shell
RAZCRYPTO_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxx
RAZCRYPTO_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxx
PHP
// config/services.php
'razcrypto' => [
    'secret_key'     => env('RAZCRYPTO_SECRET_KEY'),
    'webhook_secret' => env('RAZCRYPTO_WEBHOOK_SECRET'),
],

Get them in Dashboard → API apps. If an admin panel manages the keys, store them encrypted in the database instead (see Laravel: full integration).

3. Quick example

PHP
<?php
require 'vendor/autoload.php';

$rc = new \RazCrypto\Client(getenv('RAZCRYPTO_SECRET_KEY'));

// Create a payment
$payment = $rc->payments()->create([
    'amount'       => '49.00',          // decimal string
    'currency'     => 'USD',            // or INR, EUR …; converted to crypto at checkout
    'reference_id' => $order->id,       // your order id; comes back in webhooks and the signature
    'redirect_url' => 'https://shop.example/thanks', // website flow only
], 'order_' . $order->id);              // idempotency key: a retry never creates a duplicate

// Website: redirect the customer. App: return checkout_url to the app.
header('Location: ' . $payment['checkout_url']);
PHP
// Check a payment from your server (source of truth)
$p = $rc->payments()->retrieve('pay_…');
if ($p['status'] === 'paid') { /* fulfil */ }

status is one of pending, confirming, paid, underpaid, expired, cancelled. Only paid means the money arrived.

4. Verify webhooks

PHP
use RazCrypto\Webhook;
use RazCrypto\Exception\SignatureVerificationError;

$raw = file_get_contents('php://input');           // the raw body, exactly as received
try {
    $event = Webhook::verify($raw, getallheaders(), getenv('RAZCRYPTO_WEBHOOK_SECRET'));
} catch (SignatureVerificationError $e) {
    http_response_code(400);
    exit;
}

$payment = $event['data']['object'];               // the full payment object
if ($event['type'] === 'payment.paid') {
    markOrderPaid($payment['reference_id'], $payment['id']);
}
http_response_code(200);

In Laravel pass $request->getContent() and $request->headers->all(). Answer 2xx within 10 seconds. Retries reuse the same webhook-id header, so store it and skip repeats. Details: Webhooks.

5. Verify the checkout signature

Mobile SDKs and checkout.js return payment_id, reference_id, status and signature after a payment. The website redirect adds the same values to redirect_url.

PHP
use RazCrypto\CheckoutSignature;

if (!CheckoutSignature::isValid($params, getenv('RAZCRYPTO_WEBHOOK_SECRET'))) {
    // not from RazCrypto: do not trust it, wait for the webhook
}

A valid signature proves the values came from RazCrypto. Still call retrieve() (or wait for the webhook) before you ship.

Laravel: full integration for a mobile app

The app (Flutter, Android or React Native) never holds a secret. It calls these endpoints:

Method + pathAuthPurpose
GET /api/payment-gateways—Payment options that the admin turned on
POST /api/payments/razcrypto/createuserCreate the order + RazCrypto payment, return checkout_url
POST /api/payments/razcrypto/verifyuserCheck the checkout signature and the real status
GET /api/payments/razcrypto/status/{paymentId}userPoll while the payment confirms
POST /api/webhooks/razcryptosignatureRazCrypto → your server

Laravel 11+: run php artisan install:api once if routes/api.php does not exist yet. Routes in api.php have no CSRF check, which the webhook needs.

Migration

PHP
// database/migrations/2026_10_21_000000_razcrypto.php
Schema::create('payment_gateways', function (Blueprint $t) {
    $t->id();
    $t->string('gateway')->unique();              // 'razorpay', 'razcrypto' …
    $t->string('display_name');                   // "Pay with Crypto (USDT)"
    $t->boolean('enabled')->default(false);
    $t->string('mode')->default('test');          // test | live
    $t->string('publishable_key')->nullable();    // pk_… (optional)
    $t->text('secret_key_test')->nullable();      // encrypted
    $t->text('secret_key_live')->nullable();      // encrypted
    $t->text('webhook_secret_test')->nullable();  // encrypted
    $t->text('webhook_secret_live')->nullable();  // encrypted
    $t->unsignedInteger('sort_order')->default(1);
    $t->decimal('min_amount', 12, 2)->nullable();
    $t->decimal('max_amount', 12, 2)->nullable();
    $t->timestamps();
});

Schema::table('orders', function (Blueprint $t) {
    $t->string('gateway')->default('razorpay');
    $t->string('gateway_payment_id')->nullable()->unique();  // pay_…
    $t->string('gateway_status')->nullable();                // pending / confirming / paid / failed …
    $t->timestamp('paid_at')->nullable();
});

Schema::create('processed_webhooks', function (Blueprint $t) {
    $t->id();
    $t->string('webhook_id')->unique();                      // header "webhook-id"
    $t->timestamps();
});

Model (secrets stored encrypted)

PHP
// app/Models/PaymentGateway.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PaymentGateway extends Model
{
    protected $guarded = [];
    protected $casts = [
        'enabled'             => 'boolean',
        'secret_key_test'     => 'encrypted',
        'secret_key_live'     => 'encrypted',
        'webhook_secret_test' => 'encrypted',
        'webhook_secret_live' => 'encrypted',
    ];
    protected $hidden = ['secret_key_test', 'secret_key_live', 'webhook_secret_test', 'webhook_secret_live'];

    public function secretKey(): ?string
    {
        return $this->mode === 'live' ? $this->secret_key_live : $this->secret_key_test;
    }

    public function webhookSecret(): ?string
    {
        return $this->mode === 'live' ? $this->webhook_secret_live : $this->webhook_secret_test;
    }
}

Admin panel settings

Add a RazCrypto card next to your other gateways that edits the razcrypto row:

FieldValue
Enabledon / off. Off = the app does not show crypto
Modetest / live
Publishable keypk_test_… / pk_live_…
Secret key (test, live)sk_test_…, sk_live_…. Show masked (sk_live_••••1234)
Webhook signing secret (test, live)whsec_…. Show masked
Display name, sort order, min / max amountoptional

When the admin saves an empty secret field, keep the old value. Clear any settings cache after saving.

Service

PHP
// app/Services/RazCrypto.php
namespace App\Services;

use App\Models\PaymentGateway;
use RazCrypto\Client;

class RazCrypto
{
    public PaymentGateway $cfg;
    public Client $client;

    public function __construct()
    {
        $this->cfg = PaymentGateway::where('gateway', 'razcrypto')->firstOrFail();
        abort_unless($this->cfg->secretKey(), 503, 'RazCrypto keys are not set in the admin panel');
        $this->client = new Client($this->cfg->secretKey(), ['timeout' => 20, 'max_retries' => 2]);
    }

    /** RazCrypto status → the status the app understands */
    public static function appStatus(string $status): string
    {
        return match ($status) {
            'paid' => 'completed',
            'expired', 'cancelled' => 'failed',
            default => 'pending',           // pending, confirming, underpaid
        };
    }
}

Routes

PHP
// routes/api.php
use App\Http\Controllers\RazCryptoController;

Route::get('/payment-gateways', [RazCryptoController::class, 'gateways']);

Route::middleware('auth:sanctum')->group(function () {
    Route::post('/payments/razcrypto/create', [RazCryptoController::class, 'create']);
    Route::post('/payments/razcrypto/verify', [RazCryptoController::class, 'verify']);
    Route::get('/payments/razcrypto/status/{paymentId}', [RazCryptoController::class, 'status']);
});

Route::post('/webhooks/razcrypto', [RazCryptoController::class, 'webhook']); // no auth: the signature is the auth

Controller

PHP
// app/Http/Controllers/RazCryptoController.php
namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\PaymentGateway;
use App\Services\RazCrypto;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use RazCrypto\CheckoutSignature;
use RazCrypto\Exception\SignatureVerificationError;
use RazCrypto\Webhook;

class RazCryptoController extends Controller
{
    /** Options the admin turned on, in admin order. */
    public function gateways()
    {
        return PaymentGateway::where('enabled', true)->orderBy('sort_order')
            ->get(['gateway', 'display_name', 'sort_order', 'min_amount', 'max_amount']);
    }

    public function create(Request $request)
    {
        $request->validate(['amount' => 'required|numeric|min:1']);
        $rc = new RazCrypto();

        // The server decides the amount (validate it against your product / wallet rules)
        $order = Order::create([
            'user_id'        => $request->user()->id,
            'amount'         => $request->amount,
            'gateway'        => 'razcrypto',
            'gateway_status' => 'pending',
        ]);

        $payment = $rc->client->payments()->create([
            'amount'       => number_format((float) $order->amount, 2, '.', ''),
            'currency'     => 'INR',
            'reference_id' => (string) $order->id,
            'description'  => 'Order #' . $order->id,
            'metadata'     => ['user_id' => (string) $order->user_id],
        ], 'order_' . $order->id);

        $order->update(['gateway_payment_id' => $payment['id']]);

        return response()->json([
            'order_id'     => $order->id,
            'payment_id'   => $payment['id'],
            'checkout_url' => $payment['checkout_url'],
        ]);
    }

    public function verify(Request $request)
    {
        $rc = new RazCrypto();
        $data = $request->only(['payment_id', 'reference_id', 'status', 'signature']);

        if (!CheckoutSignature::isValid($data, $rc->cfg->webhookSecret())) {
            return response()->json(['message' => 'Invalid signature'], 400);
        }
        $order = Order::where('gateway_payment_id', $data['payment_id'] ?? '')
            ->where('user_id', $request->user()->id)->firstOrFail();

        $p = $rc->client->payments()->retrieve($order->gateway_payment_id); // ask RazCrypto, not the app
        $this->sync($p);

        return ['status' => RazCrypto::appStatus($p['status'])];
    }

    public function status(Request $request, string $paymentId)
    {
        $order = Order::where('gateway_payment_id', $paymentId)
            ->where('user_id', $request->user()->id)->firstOrFail();
        if ($order->gateway_status === 'paid') {
            return ['status' => 'completed'];
        }
        $p = (new RazCrypto())->client->payments()->retrieve($paymentId);
        $this->sync($p);

        return ['status' => RazCrypto::appStatus($p['status'])];
    }

    public function webhook(Request $request)
    {
        $rc = new RazCrypto();
        try {
            $event = Webhook::verify($request->getContent(), $request->headers->all(), $rc->cfg->webhookSecret());
        } catch (SignatureVerificationError $e) {
            return response('invalid signature', 400);
        }

        $webhookId = (string) $request->header('webhook-id');
        if (DB::table('processed_webhooks')->where('webhook_id', $webhookId)->exists()) {
            return response('ok', 200);                    // a retry we already handled
        }

        if (str_starts_with($event['type'], 'payment.')) {
            $this->sync($event['data']['object']);         // the full payment object
        }

        DB::table('processed_webhooks')->insert(['webhook_id' => $webhookId, 'created_at' => now(), 'updated_at' => now()]);
        return response('ok', 200);
    }

    /** Apply a RazCrypto payment to its order. Safe to call many times. */
    private function sync(array $p): void
    {
        DB::transaction(function () use ($p) {
            $order = Order::lockForUpdate()->where('gateway_payment_id', $p['id'])->first();
            if (!$order || $order->gateway_status === 'paid') {
                return;                                     // unknown, or already fulfilled
            }
            if ($p['status'] !== 'paid') {
                $order->update(['gateway_status' => $p['status']]);
                return;
            }
            if ((string) $order->id !== (string) $p['reference_id']) {
                return;                                     // payment belongs to another order
            }
            $order->update(['gateway_status' => 'paid', 'paid_at' => now()]);
            // Fulfil here, exactly once: credit the wallet, unlock the plan, send the receipt …
        });
    }
}

Test it

Shell
php artisan tinker
>>> $rc = new \RazCrypto\Client(config('services.razcrypto.secret_key')); // a sk_test_ key
>>> $rc->payments()->simulate('pay_…', 'paid');   // runs the whole flow, webhook included

Then check Dashboard → API apps → Webhooks: the delivery should show your 200. Try underpaid, expired and cancelled too.

The app side: Flutter · Android · React Native. For a website, return checkout_url and redirect, or open it with checkout.js.

API

AreaMethods
Paymentspayments()->create($params, $idempotencyKey), retrieve($id), all($params), methods($id), quote($id, $chain, $coin), cancel($id), simulate($id, $outcome) (test mode)
Payment linkspaymentLinks()->create(…), retrieve, all, update, deactivate
Otherschains(), rates(['USDT', 'BNB'], 'USD'), merchant(), event($id)

Errors. API errors throw RazCrypto\Exception\ApiError (HTTP status, code, param, request id). Network problems throw RazCrypto\Exception\ConnectionError. Network errors, 429 and 5xx are retried with the same idempotency key. Options: new Client($key, ['timeout' => 30, 'max_retries' => 2]). See Errors.

Troubleshooting

ProblemFix
Webhook always 400Use the raw body ($request->getContent()), not $request->all(). Check test vs live signing secret.
Webhook 419The route is in web.php. Move it to api.php or exclude it from CSRF.
401 api_key_invalidWrong or mixed key: sk_test_ for test mode, sk_live_ for live.
Order paid twiceStore webhook-id and make fulfilment idempotent (see sync()).