Files
portal-api/app/Http/Controllers/Api/Service/PaymentController.php
T

75 lines
2.6 KiB
PHP

<?php
namespace App\Http\Controllers\Api\Service;
use App\Http\Controllers\Controller;
use App\Jobs\VirtualMachine\ProcessOrderPaymentJob;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class PaymentController extends Controller
{
/**
* Thanh toán order bằng credit
* POST /v1/services/orders/{order_id}/pay
*/
public function payOrder(Request $request, $orderId)
{
try {
$customer = $request->user();
$order = Order::with(['invoice', 'orderItems', 'customer'])
->where('id', $orderId)
->where('customer_id', $customer->id)
->first();
if (!$order) {
return response()->json([
'error' => true,
'message' => 'Không tìm thấy đơn hàng'
], 404);
}
if ($order->status == 2) { // Already paid
return response()->json([
'error' => true,
'message' => 'Đơn hàng đã được thanh toán'
], 400);
}
// Kiểm tra số dư tài khoản (total)
if ($customer->total < $order->amount) {
return response()->json([
'error' => true,
'message' => 'Số dư không đủ để thanh toán',
'data' => [
'required' => $order->amount,
'current_total' => $customer->total,
'shortage' => $order->amount - $customer->total
]
], 400);
}
// Dispatch job để xử lý thanh toán và tạo VM
ProcessOrderPaymentJob::dispatch($order);
return response()->json([
'error' => false,
'message' => 'Đơn hàng đang được xử lý. Bạn sẽ nhận được thông báo khi hoàn tất.',
'notice' => 'Dịch vụ VPS sẽ được khởi tạo trong vòng 5-10 phút. Vui lòng đợi trong giây lát.',
'data' => [
'order_id' => $order->id,
'order_num' => $order->order_num,
'status' => 'processing'
]
]);
} catch (\Exception $e) {
Log::error('Pay order error: ' . $e->getMessage());
return response()->json([
'error' => true,
'message' => 'Có lỗi xảy ra khi thanh toán đơn hàng'
], 500);
}
}
}