Laravel 5.5集成Midtrans支付API:ixudra/curl代码实现求助
Hey there! Let's walk through fixing and improving your Midtrans token API implementation using the ixudra/curl library in Laravel. I spot a few key issues and best practices to apply:
1. Fix the withData() overwriting problem
Right now, you’re calling withData() multiple times, which will overwrite the previous data instead of merging it. Midtrans requires all payment-related fields in a single JSON payload, so combine all your parameters into one array:
public function index() { $response = Curl::to('https://api.sandbox.midtrans.com/v2/token') ->withHeader('Content-Type: application/json') ->withHeader('Accept: application/json') ->withHeader('Authorization: Basic ' . base64_encode('YOUR_MIDTRANS_SERVER_KEY:')) ->withData([ 'card_number' => '4811111111111114', 'card_cvv' => '123', 'card_exp_month' => '12', // Required field you missed 'card_exp_year' => '2028', // Required field you missed 'client_key' => 'YOUR_MIDTRANS_CLIENT_KEY', // Mandatory for token generation 'gross_amount' => 10000 // Required to define transaction value ]) ->post(); // Critical: Midtrans token API requires POST request }
2. Correct the Authorization header format
Midtrans uses HTTP Basic Auth, which requires your server key followed by a colon (:) encoded in Base64. Don’t hardcode the encoded string directly—generate it dynamically to avoid mistakes, and store keys securely in Laravel's .env file:
// Generate auth header dynamically $authHeader = 'Basic ' . base64_encode(env('MIDTRANS_SERVER_KEY') . ':');
Add these to your .env file:
MIDTRANS_SERVER_KEY=your_sandbox_server_key MIDTRANS_CLIENT_KEY=your_sandbox_client_key
3. Add proper response handling and error catching
Your current code doesn’t handle failed requests or parse the response. Add error handling and auto-parse JSON responses to make debugging easier:
public function index() { try { $response = Curl::to('https://api.sandbox.midtrans.com/v2/token') ->withHeader('Content-Type: application/json') ->withHeader('Accept: application/json') ->withHeader('Authorization: Basic ' . base64_encode(env('MIDTRANS_SERVER_KEY') . ':')) ->withData([ 'card_number' => '4811111111111114', 'card_cvv' => '123', 'card_exp_year' => '2028', 'card_exp_month' => '12', 'client_key' => env('MIDTRANS_CLIENT_KEY'), 'gross_amount' => 10000 ]) ->asJson(true) // Auto-convert response to PHP object/array ->post(); // Check if token was generated successfully if (isset($response->token_id)) { // Use $response->token_id for subsequent payment steps return response()->json(['status' => 'success', 'token' => $response->token_id]); } else { return response()->json(['status' => 'error', 'message' => $response->status_message ?? 'Failed to generate token'], 400); } } catch (\Exception $e) { // Catch network errors, invalid API keys, or server issues return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500); } }
4. Validate user input (if applicable)
If this endpoint accepts user-submitted card details, always validate the input first to avoid invalid requests to Midtrans:
$validated = request()->validate([ 'card_number' => 'required|numeric|digits:16', 'card_cvv' => 'required|numeric|digits_between:3,4', 'card_exp_month' => 'required|numeric|between:1,12', 'card_exp_year' => 'required|numeric|min:' . date('Y'), 'gross_amount' => 'required|numeric|min:1' ]); // Pass the validated data to withData() ->withData($validated + ['client_key' => env('MIDTRANS_CLIENT_KEY')])
5. Verify Midtrans prerequisites
Double-check these to avoid common failures:
- Ensure you’re using Sandbox API keys (not Production) since you’re hitting the sandbox endpoint
- Confirm the test card
4811111111111114is valid (it’s one of Midtrans’ official test Visa cards) - Make sure your server allows outgoing requests to
api.sandbox.midtrans.com(no firewall/blocking rules)
内容的提问来源于stack exchange,提问作者Billyanto Hendrik




