Introduction

In this tutorial, we'll explore how to integrate and use the NMI (Network Merchants, Inc.) payment gateway in a Laravel application. We'll cover creating a service class to handle customer vault creation and payment processing using CURL requests. This approach allows you to securely store customer payment details and process transactions using the NMI API.

Prerequisites

  • Basic knowledge of the Laravel framework.
  • Familiarity with PHP and the CURL library.
  • Access to an NMI account and API credentials.

Step 1: Setting Up the NMI Service Class

First, we'll create a service class in Laravel to manage the interaction with the NMI API.

  1. Create the Service Class:

Create a new file in the app/Services directory named NMI.php.


   namespace App\Services;

   use Illuminate\Support\Facades\Http;

   class NMI
   {
       protected $securityKey, $url;
       protected $production;

       public function __construct()
       {
           $this->production = env('APP_ENV') === 'production';
           $this->securityKey = config('nmi.security_key');
           $this->url = 'https://secure.nmi.com/api/transact.php';
       }
   }

This class initializes with the NMI security key and API URL. It also determines if the application is running in production mode.

  1. Configure the NMI Security Key:

Add your NMI security key to your configuration file. In config/nmi.php, add:


   return [
       'security_key' => env('NMI_SECURITY_KEY', 'your-security-key-here'),
   ];

In your .env file, add:


   NMI_SECURITY_KEY=your-security-key-here

Step 2: Adding Customer Vault Functionality

The NMI API allows you to securely store customer payment details in a "vault" for future transactions. We'll create a method to add customer details to the vault.

  1. Add the addCustomerVault Method:

Inside the NMI class, add the following method:


   public function addCustomerVault($creditCard)
   {
       $data = [
           'ccnumber' => $creditCard['cc_number'],
           'ccexp' => $creditCard['exp_date'],
           'cvv' => $creditCard['cvv'],
           'customer_vault' => 'add_customer',
           'security_key' => $this->securityKey,
       ];

       if ($this->production === false) {
           $data['test_mode'] = 'enabled';
       }

       $createVaultCurl = curl_init();
       curl_setopt_array($createVaultCurl, [
           CURLOPT_URL => $this->url,
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_POST => true,
           CURLOPT_POSTFIELDS => http_build_query($data),
           CURLOPT_SSL_VERIFYHOST => false,
           CURLOPT_SSL_VERIFYPEER => false,
       ]);
       $createVaultResponse = curl_exec($createVaultCurl);
       curl_close($createVaultCurl);

       \Log::info('NMI Vault Response: ' . $createVaultResponse);

       if ($createVaultResponse === false) {
           return [
               'responsetext' => 'error',
               'error' => 'Customer vault creation failed',
           ];
       }

       parse_str($createVaultResponse, $vaultResponseArray);
       return isset($vaultResponseArray['customer_vault_id']) ? $vaultResponseArray['customer_vault_id'] : null;
   }

This method takes in credit card details, formats them, and sends a CURL request to the NMI API to add the customer to the vault. If the application is in test mode, it returns a mock response. The method logs the response using Laravel's standard logging mechanism.

Step 3: Processing Payments Using Customer Vault

Once a customer is added to the vault, you can process payments using their vault ID. Let’s add a method for this.

  1. Add the processPaymentUsingVault Method:

Add the following method to the NMI class:


   public function processPaymentUsingVault($customerVaultId, $totalAmount)
   {
       $data = [
           'security_key' => $this->securityKey,
           'customer_vault_id' => $customerVaultId,
           'amount' => $totalAmount,
       ];

       if ($this->production === false) {
           $data['test_mode'] = 'enabled';
       }

       $curl = curl_init();
       curl_setopt_array($curl, [
           CURLOPT_URL => $this->url,
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_POST => true,
           CURLOPT_POSTFIELDS => http_build_query($data),
           CURLOPT_SSL_VERIFYHOST => false,
           CURLOPT_SSL_VERIFYPEER => false,
       ]);
       $response = curl_exec($curl);
       curl_close($curl);

       if ($response === false) {
           return [
               'responsetext' => 'error',
               'error' => 'Payment processing failed',
           ];
       }

       \Log::info('NMI Payment Response: ' . $response);

       parse_str($response, $parsedResponse);

       return $parsedResponse;
   }

This method uses the customer’s vault ID to process a payment for the specified amount. It handles test mode and logs the payment response using Laravel’s info logging.

Step 4: Testing and Using the Service

Now that the service is set up, you can use it in your Laravel controllers or services.

  1. Example Usage:

In a controller, you can use the NMI service as follows:


   use App\Services\NMI;

   class PaymentController extends Controller
   {
       protected $nmi;

       public function __construct(NMI $nmi)
       {
           $this->nmi = $nmi;
       }

       public function storeCustomer(Request $request)
       {
           $creditCard = $request->only(['cc_number', 'exp_date', 'cvv']);
           $customerVaultId = $this->nmi->addCustomerVault($creditCard);

           return response()->json(['customer_vault_id' => $customerVaultId]);
       }

       public function processPayment(Request $request)
       {
           $customerVaultId = $request->input('customer_vault_id');
           $amount = $request->input('amount');
           $paymentResponse = $this->nmi->processPaymentUsingVault($customerVaultId, $amount);

           return response()->json($paymentResponse);
       }
   }

Conclusion

By following this tutorial, you've learned how to integrate the NMI payment gateway with your Laravel application. You've created a service class to manage customer vaults and process payments using the NMI API, including handling test mode and logging responses using Laravel’s default logging system.

This setup provides a solid foundation for securely handling payments in your application, with flexibility for production and testing environments.