Laravel跨项目API调用问题:如何实现第二个项目调用订单API
Hey there! Let's walk through how to set up the API call from your second Laravel project to the first one. I've implemented similar cross-app integrations before, so here are the most practical approaches:
1. Use Laravel's Built-in HTTP Client (Recommended)
Laravel comes with a clean wrapper around Guzzle that makes HTTP requests super straightforward—no extra setup needed if you're on Laravel 7 or newer.
Step-by-Step Implementation:
In your second project, create a service class (or use a controller method) to handle the API call. Here's a practical example:
use Illuminate\Support\Facades\Http; use Illuminate\Http\Response; // Inside your controller/service method public function getOrderStatus(int $orderId) { // Pull API config from .env (best practice to avoid hardcoding!) $apiBaseUrl = env('PROJECT_A_API_BASE', 'http://payment.oo/api'); $apiToken = env('PROJECT_A_API_TOKEN'); try { $response = Http::withToken($apiToken) ->timeout(10) // Set a reasonable timeout to avoid hanging requests ->retry(3, 100) // Retry 3 times with 100ms delay for network blips ->get("{$apiBaseUrl}/orders/{$orderId}"); if ($response->successful()) { $orderData = $response->json(); // Process the order status, e.g.: return response()->json(['payment_status' => $orderData['payment_status']], Response::HTTP_OK); } // Handle non-success responses (like 404 for missing orders) return response()->json(['error' => 'Order not found or API error'], $response->status()); } catch (\Exception $e) { // Catch connection issues, timeouts, etc. return response()->json(['error' => 'Failed to connect to order service'], Response::HTTP_SERVICE_UNAVAILABLE); } }Secure your first project's API: Don't leave the endpoint open to the public! Use Laravel Sanctum or Passport to add token authentication:
- For Sanctum: Generate an API token in your first project (for the second app to use), then add the
auth:sanctummiddleware to yourapi.phproute:// In project A's routes/api.php Route::get('/orders/{order}', [OrderController::class, 'show'])->middleware('auth:sanctum');
- For Sanctum: Generate an API token in your first project (for the second app to use), then add the
2. Direct Guzzle HTTP Client Usage
If you prefer to use Guzzle directly (without Laravel's wrapper), this works just as well:
Step-by-Step Implementation:
Install Guzzle in your second project (if not already installed):
composer require guzzlehttp/guzzleWrite the API call logic:
use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Illuminate\Http\Response; public function getOrderStatus(int $orderId) { $apiBaseUrl = env('PROJECT_A_API_BASE', 'http://payment.oo/api'); $apiToken = env('PROJECT_A_API_TOKEN'); $client = new Client(); try { $response = $client->get("{$apiBaseUrl}/orders/{$orderId}", [ 'headers' => [ 'Authorization' => "Bearer {$apiToken}", 'Accept' => 'application/json', ], 'timeout' => 10, ]); $orderData = json_decode($response->getBody(), true); return response()->json(['payment_status' => $orderData['payment_status']], Response::HTTP_OK); } catch (RequestException $e) { $statusCode = $e->getResponse()?->getStatusCode() ?? Response::HTTP_SERVICE_UNAVAILABLE; $errorMessage = $e->getMessage(); return response()->json(['error' => $errorMessage], $statusCode); } }
Key Best Practices
- Store sensitive config in .env: Never hardcode API URLs or tokens in your codebase. Use environment variables and reference them via Laravel's
env()helper or config files (e.g., add entries toconfig/services.phpfor cleaner access). - Add robust error handling: Always account for timeouts, connection failures, and non-success HTTP status codes (like 404, 500) to avoid breaking your app.
- Rate limiting: Consider adding rate limiting in your first project's API to prevent abuse from the second app.
- Logging: Log failed API calls in your second project so you can debug issues quickly later.
内容的提问来源于stack exchange,提问作者Loïc

