پرش به محتویات

نمونه‌کد PHP

این نمونه بدونِ هیچ کتابخانه‌ای، فقط با curlِ خودِ PHP، کلِ جریان را پیاده می‌کند. API key را در متغیرهای محیطی بگذارید:

RABINHOOD_API_KEY=rhp_sk_…

کلاینت

RabinhoodPay.php
<?php

final class RabinhoodPay
{
    private const BASE_URL = 'https://pay.rabinhood.co/api/v2/pay/merchant';

    public function __construct(private string $apiKey) {}

    public function createPayment(string $orderId, int $amountToman, string $description,
                                  string $callbackUrl, string $returnUrl): array
    {
        return $this->request('POST', '/payments', [
            'order_id'     => $orderId,
            'amount_toman' => (string) $amountToman,
            'description'  => $description,
            'callback_url' => $callbackUrl,
            'return_url'   => $returnUrl,
        ]);
    }

    public function getPayment(string $paymentId): array
    {
        return $this->request('GET', '/payments/' . rawurlencode($paymentId));
    }

    public function verifyPayment(string $paymentId): array
    {
        return $this->request('POST', '/payments/' . rawurlencode($paymentId) . '/verify');
    }

    private function request(string $method, string $path, ?array $body = null): array
    {
        $ch = curl_init(self::BASE_URL . $path);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . $this->apiKey,
                'Content-Type: application/json',
            ],
        ]);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
        }
        $raw    = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $error  = curl_error($ch);
        curl_close($ch);

        if ($raw === false) {
            throw new RuntimeException("rabinhood: network error: $error");
        }
        $data = json_decode($raw, true) ?? ['message' => $raw];
        return ['status' => $status, 'data' => $data];
    }
}

۱. ساختِ پرداخت و هدایتِ خریدار

checkout.php
<?php
require 'RabinhoodPay.php';

$pay   = new RabinhoodPay(getenv('RABINHOOD_API_KEY'));
$order = loadOrder($_POST['order_id']); // your own order

$res = $pay->createPayment(
    $order['id'],
    $order['total_toman'],
    'Order ' . $order['id'],
    'https://shop.example/rabinhood/callback.php',
    'https://shop.example/rabinhood/return.php'
);

if ($res['status'] !== 200) {
    http_response_code(502);
    exit('Payment gateway error: ' . ($res['data']['message'] ?? ''));
}

saveOrderPayment($order['id'], $res['data']['payment_id']);

if ($res['data']['existing'] && $res['data']['pay_url'] === '') {
    exit('A payment already exists for this order.');
}

header('Location: ' . $res['data']['pay_url']);

۲. صفحهٔ بازگشت

return.php
<?php
require 'RabinhoodPay.php';

$paymentId = $_GET['payment_id'] ?? '';
if ($paymentId === '') {
    exit('Payment not found.');
}

$pay = new RabinhoodPay(getenv('RABINHOOD_API_KEY'));
$res = $pay->verifyPayment($paymentId);

if ($res['status'] === 200 && $res['data']['status'] === 'SUCCESSFUL') {
    $order = findOrderByPayment($paymentId);
    if ($order && (int) $res['data']['amount_toman'] === $order['total_toman']) {
        markOrderPaid($order['id'], $res['data']); // once only, if not already paid
        exit('Payment successful. Tracking code: ' . ($res['data']['tracking_code'] ?? '-'));
    }
}

echo 'Payment was not completed.';

۳. کال‌بک

callback.php
<?php
require 'RabinhoodPay.php';

$event     = json_decode(file_get_contents('php://input'), true);
$paymentId = is_array($event) ? (string) ($event['payment_id'] ?? '') : '';
if ($paymentId === '') {
    http_response_code(400);
    exit;
}

// The callback only notifies; verify is what settles the order.
$pay = new RabinhoodPay(getenv('RABINHOOD_API_KEY'));
$res = $pay->verifyPayment($paymentId);

if ($res['status'] === 200 && $res['data']['status'] === 'SUCCESSFUL') {
    markOrderPaid($res['data']['order_id'], $res['data']); // must be safe to repeat
}

http_response_code(200);

Tip

markOrderPaid را طوری بنویسید که اگر دو بار صدا زده شد (یک بار از صفحهٔ بازگشت و یک بار از کال‌بک)، سفارش فقط یک بار قطعی شود. مثلاً با UPDATE orders SET status='paid' WHERE id=? AND status<>'paid'.