![how to integrate cybersource payment gateway in laravel](/storage/blogs/images/1710055925Strength and growth come only through continuous effort and struggle (18).webp)
how to integrate cybersource payment gateway in laravel
- showkat ali
- 10th Mar, 2024
- 301
- 1
In today's competitive e-commerce landscape, providing a seamless and secure payment experience is critical to customer satisfaction and business growth. CyberSource is a leading payment gateway with advanced features for online transactions. This blog post explains how to integrate CyberSource into your Laravel application directly, so you can accept payments effectively without depending on third-party packages.
Prerequisites:
- A Laravel application was set up.
- A CyberSource account with API credentials (Merchant ID, Transaction Key, etc.). Click Here
- Basic understanding of Laravel routing, forms, and validation.
- Familiarity with making API requests using Laravel's
Http
facade. - Knowledge of SHA-256 hashing and HMAC generation.
Integration Steps:
-
API Credentials and Endpoint:
- Obtain your CyberSource API Key, Secret Key, and Merchant ID from your account dashboard. Sandbox Signup
- Store these credentials securely in your Laravel environment variables using
.env
file. - Define the CyberSource test endpoint URL (replace with production URL for live environment):
-
$apiEndpoint = 'https://apitest.cybersource.com/pts/v2/payments';
-
Payment Request Data:
- Create an array to hold the data you'll send to the CyberSource API:
$requestData = [ "clientReferenceInformation" => [ "code" => "TC50171_3", // Replace with your unique reference code ], "paymentInformation" => [ "card" => [ "number" => $request->card_number, // From user input "expirationMonth" => $request->expiry_month, // From user input "expirationYear" => $request->expiry_year, // From user input ], ], "orderInformation" => [ "amountDetails" => [ "totalAmount" => $request->total_amount, // From user input "currency" => "USD", ], "billTo" => [ "firstName" => $request->full_name, // From user input "lastName" => "Doe", // Can be pre-populated or from user input "address1" => "1 Market St", // Can be pre-populated or from user input "locality" => "San Francisco", // Can be pre-populated or from user input "administrativeArea" => "CA", // Can be pre-populated or from user input "postalCode" => "94105", // Can be pre-populated or from user input "country" => "US", "email" => $request->email, // From user input "phoneNumber" => "4158880000", // Can be pre-populated or from user input ], ], ];
- Replace placeholder values with actual data from your user's form submission.
- Create an array to hold the data you'll send to the CyberSource API:
-
Signature Generation:
- CyberSource requires a signature for authentication using HMAC-SHA256. Here's how to generate it:
$vCDate = gmdate('D, d M Y H:i:s T'); $digest = 'SHA-256=' . base64_encode(hash('sha256', json_encode($requestData), true)); $signatureString = '(request-target): post /pts/v2/payments' . "\n" . 'host: apitest.cybersource.com' . "\n" . 'digest: ' . $digest . "\n" . 'v-c-merchant-id: ' . env('MERCHANT_ID'); $signature = base64_encode(hash_hmac('sha256', $signatureString, base64_decode(env('API_SECRET')), true));
- CyberSource requires a signature for authentication using HMAC-SHA256. Here's how to generate it:
-
Sending the Request:
- Use Laravel's
Http
facade to send a POST request with the prepared data and headers:$headers = [ 'host' => 'apitest.cybersource.com', 'signature' => 'keyid="' . env('API_KEY') . '", algorithm="HmacSHA256", headers="(request-target) host digest v-c-merchant-id", signature="' . $signature . '"', 'digest' => $digest, 'v-c-merchant-id' => env('MERCHANT_ID'), 'v-c-date' => 'Content-Type' => 'application/json', ]; $response = Http::withHeaders($headers)->post($apiEndpoint, $requestData); // Process the response if ($response->successful()) { $result = $response->json(); if ($result['status'] == "AUTHORIZED") { // Payment successful! $transaction = new Transaction(); $transaction->fullname = $request->full_name; $transaction->transaction_id = $result['id']; $transaction->credit_to = $request->credit_to; // Assuming credit_to field exists $transaction->payment_type = $request->payment_type; // Assuming payment_type field exists $transaction->description = $request->description; // Assuming description field exists $transaction->amount = $request->total_amount; $transaction->charged_amount = $request->total_amount; $transaction->email = $request->email; $transaction->phone = $request->phone; $transaction->status = $result['status']; $transaction->save(); return back()->with('success', 'Payment Successfully!'); } else { // Payment failed! Handle error message $errorMessage = "Payment Failed: " . $result['message']; return view('cybersource.payment-error', ['errorMessage' => $errorMessage]); } } else { // Handle general API request errors $errorMessage = "An error occurred while processing your payment. Please try again."; return view('cybersource.payment-error', ['errorMessage' => $errorMessage]); }
Explanation:
- We check for a successful HTTP response using
$response->successful()
. - If successful, we parse the JSON response and check for the
status
. - For a successful transaction (
"AUTHORIZED"
status), we create a newTransaction
model instance and populate it with relevant details from the request and response. - We save the transaction to the database and redirect back with a success message.
- If the transaction fails, we extract the error message from the response and display it in a dedicated payment error view (
cybersource.payment-error
). - For any general API request errors (e.g., network issues), we display a generic error message in the payment error view.
This concludes the integration of CyberSource into your Laravel application without relying on a package. Remember to test the functionality thoroughly in both development and testing environments before deploying to production.
- We check for a successful HTTP response using
- Use Laravel's
We are Recommending you
-
A Step-by-Step Guide:How to integrate stripe payment into laravel 10
-
How to Use Quill Rich Text Editor Laravel 10: A Comprehensive Guide
-
how to integrate cybersource payment gateway in laravel
-
Pusher real-time Notification with Laravel and React.js
-
Laravel Many-to-Many Relationships: A Comprehensive Guide
0 Comments
Please log in to leave a comment.
Latest blog
Related Interview Questions
Core PHP Interview Questions (2023)
18th Aug