feat(api): implement payment gateway integration

Add Zarinpal configuration options and implement the core payment
infrastructure, including the Payment model, migration, service
layer, and API controller.
This commit is contained in:
Kazem Alghasi 2026-08-05 23:49:33 +03:30
parent 8d228993f9
commit 50ae20b14a
5 changed files with 379 additions and 0 deletions

View File

@ -0,0 +1,103 @@
<?php
namespace App\Http\Controllers\Api;
use App\Models\User;
use App\Models\Wallet;
use App\Services\PaymentGatewayService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class PaymentController
{
public function __construct(protected PaymentGatewayService $gateway) {}
public function request(Request $request): JsonResponse
{
$user = $request->user();
if (!$user) {
return response()->json(['message' => 'Unauthorized'], 401);
}
try {
$validated = $request->validate([
'amount' => ['required', 'numeric', 'min:1000'],
'description' => ['nullable', 'string', 'max:500'],
]);
} catch (ValidationException $e) {
return response()->json([
'message' => 'Validation failed',
'errors' => $e->errors(),
], 422);
}
$wallet = $user->wallet()->first();
if (!$wallet) {
$wallet = Wallet::create([
'user_id' => $user->id,
'balance' => 0,
]);
}
$result = $this->gateway->requestPayment(
$user,
$validated['amount'],
$validated['description'] ?? 'شارچ کیف پول'
);
if (!$result['success']) {
return response()->json($result, 400);
}
return response()->json([
'message' => 'درخواست پرداخت ایجاد شد',
'authority' => $result['authority'],
'payment_url' => $result['payment_url'] ?? null,
'mock' => $result['mock'] ?? false,
]);
}
public function callback(Request $request): JsonResponse
{
$authority = $request->query('Authority');
$status = $request->query('Status');
if (!$authority) {
return response()->json(['message' => 'Authority not provided'], 400);
}
if ($status !== 'OK') {
return response()->json([
'message' => 'پرداخت لغو شد.',
'status' => $status,
]);
}
$result = $this->gateway->verifyPayment($authority);
if (!$result['success']) {
return response()->json($result, 400);
}
return response()->json([
'message' => $result['message'],
'ref_id' => $result['ref_id'],
'amount' => $result['amount'],
]);
}
public function status(Request $request, string $authority): JsonResponse
{
$result = $this->gateway->checkPayment($authority);
if (!$result['success']) {
return response()->json($result, 404);
}
return response()->json($result);
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Payment extends Model
{
protected $fillable = [
'user_id',
'wallet_id',
'gateway',
'merchant_id',
'authority',
'ref_id',
'amount',
'currency',
'status',
'description',
'paid_at',
];
protected $casts = [
'amount' => 'integer',
'paid_at' => 'datetime',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function wallet(): BelongsTo
{
return $this->belongsTo(Wallet::class);
}
}

View File

@ -0,0 +1,203 @@
<?php
namespace App\Services;
use App\Models\Payment;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class PaymentGatewayService
{
public function __construct(protected Payment $payment) {}
public function requestPayment(User $user, float $amount, string $description = null): array
{
$merchantId = config('ifnex.zarinpal_merchant_id');
if (!$merchantId || $merchantId === 'change-me') {
return $this->mockPayment($user, $amount, $description);
}
$callbackUrl = config('ifnex.zarinpal_callback_url', url('/payment/callback'));
$response = Http::post('https://api.zarinpal.com/pg/v4/payment/request', [
'merchant_id' => $merchantId,
'amount' => (int) ($amount * 10),
'callback_url' => $callbackUrl,
'description' => $description ?? 'شارچ کیف پول IFNEX',
'metadata' => [
'user_id' => $user->id,
'email' => $user->email,
],
]);
$data = $response->json();
if (($data['data']['code'] ?? 0) !== 100) {
Log::error('ZarinPal payment request failed', ['response' => $data]);
return [
'success' => false,
'message' => 'خطا در درخواست پرداخت.',
'code' => $data['data']['code'] ?? 0,
];
}
$authority = $data['data']['authority'];
$this->payment->create([
'user_id' => $user->id,
'gateway' => 'zarinpal',
'merchant_id' => $merchantId,
'authority' => $authority,
'amount' => (int) ($amount * 10),
'currency' => 'IRR',
'status' => 'pending',
'description' => $description,
]);
return [
'success' => true,
'authority' => $authority,
'payment_url' => "https://www.zarinpal.com/pg/StartPay/{$authority}",
];
}
public function verifyPayment(string $authority, string $refId = null): array
{
$merchantId = config('ifnex.zarinpal_merchant_id');
$payment = $this->payment->where('authority', $authority)->first();
if (!$payment) {
return [
'success' => false,
'message' => 'تراکنش پیدا نشد.',
];
}
if ($payment->status !== 'pending') {
return [
'success' => false,
'message' => 'این تراکنش قبلاً بررسی شده است.',
];
}
if (!$merchantId || $merchantId === 'change-me') {
return $this->mockVerify($payment);
}
$response = Http::post("https://api.zarinpal.com/pg/v4/payment/verify/{$merchantId}", [
'merchant_id' => $merchantId,
'authority' => $authority,
'amount' => $payment->amount,
]);
$data = $response->json();
if (($data['data']['code'] ?? 0) !== 100) {
$payment->update(['status' => 'failed']);
return [
'success' => false,
'message' => 'تأیید پرداخت ناموفق بود.',
'code' => $data['data']['code'] ?? 0,
];
}
$refId = $data['data']['ref_id'] ?? null;
$payment->update([
'status' => 'completed',
'ref_id' => $refId,
'paid_at' => now(),
]);
if ($payment->wallet_id) {
$wallet = Wallet::find($payment->wallet_id);
if ($wallet) {
$wallet->increment('balance', $payment->amount);
}
}
return [
'success' => true,
'message' => 'پرداخت با موفقیت تأیید شد.',
'ref_id' => $refId,
'amount' => $payment->amount,
];
}
public function checkPayment(string $authority): array
{
$payment = $this->payment->where('authority', $authority)->first();
if (!$payment) {
return [
'success' => false,
'message' => 'تراکنش پیدا نشد.',
];
}
return [
'success' => true,
'status' => $payment->status,
'amount' => $payment->amount,
'ref_id' => $payment->ref_id,
'paid_at' => $payment->paid_at?->toIso8601String(),
];
}
private function mockPayment(User $user, float $amount, string $description = null): array
{
$this->payment->create([
'user_id' => $user->id,
'gateway' => 'zarinpal',
'amount' => (int) ($amount * 10),
'currency' => 'IRR',
'status' => 'completed',
'description' => $description,
'paid_at' => now(),
]);
$user->wallet()->updateOrCreate(
[],
['balance' => 0]
);
$wallet = $user->wallet()->first();
$wallet->increment('balance', (int) ($amount * 10));
return [
'success' => true,
'authority' => 'MOCK-' . strtoupper(uniqid()),
'payment_url' => null,
'mock' => true,
];
}
private function mockVerify(Payment $payment): array
{
$payment->update([
'status' => 'completed',
'ref_id' => 'MOCK-' . strtoupper(uniqid()),
'paid_at' => now(),
]);
if ($payment->wallet_id) {
$wallet = Wallet::find($payment->wallet_id);
if ($wallet) {
$wallet->increment('balance', $payment->amount);
}
}
return [
'success' => true,
'message' => 'پرداخت موقت تأیید شد (sandbox).',
'ref_id' => $payment->ref_id,
'amount' => $payment->amount,
];
}
}

View File

@ -24,4 +24,7 @@ return [
'currency_api_key' => env('CURRENCY_API_KEY'),
'zarinpal_merchant_id' => env('ZARINPAL_MERCHANT_ID'),
'zarinpal_callback_url' => env('ZARINPAL_CALLBACK_URL', 'http://localhost/payment/callback'),
];

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('wallet_id')->nullable()->constrained()->nullOnDelete();
$table->string('gateway')->default('zarinpal');
$table->string('merchant_id')->nullable();
$table->string('authority')->nullable();
$table->string('ref_id')->nullable();
$table->unsignedBigInteger('amount');
$table->string('currency')->default('IRR');
$table->string('status')->default('pending');
$table->text('description')->nullable();
$table->timestamp('paid_at')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('payments');
}
};