Loading image
how to integrate cybersource payment gateway in laravel

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:

  1. 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';
      
  2. 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.
  3. 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));
      
  4. 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]);
         }
      
      
      

       

       

      Source Code here : https://github.com/Showkiip/laravel-cybersource

      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 new Transaction 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.

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

0 Comments

Please log in to leave a comment.