Using for Transactions

Process one-time sales for recurring customers using vault tokens with your merchant API key

Process one-time sales using vault tokens instead of raw payment data. This approach is ideal for serving returning customers without collecting payment information again.

📘

Vault tokens eliminate the need to handle sensitive payment data for repeat transactions.

Server-side Example

The following is an example code snippet. Full parameter support can be seen in our docs under the "Credit Card - Sale" request.

// Process sale using vault token
router.post('/vault-sale', async (req, res) => {
  try {
    const { customerVaultId, amount } = req.body;
    
    // customerVaultId should be the ID returned when adding a vault entry
    const response = await axios.post('https://secure.networkmerchants.com/api/transact.php', {
      security_key: '{user.privateApiKey}',
      type: 'sale',
      customer_vault_id: customerVaultId,
      amount: amount
    });
    
    if (response.data.response === '1') {
      return res.json({
        success: true,
        transactionId: response.data.transactionid,
        authCode: response.data.authcode,
        responseText: response.data.responsetext
      });
    } else {
      return res.json({
        success: false,
        error: response.data.responsetext
      });
    }
  } catch (error) {
    console.error('Error processing vault sale:', error);
    return res.status(500).json({
      success: false,
      error: 'An error occurred while processing vault sale'
    });
  }
});
# Process sale using vault token
import requests

def process_vault_sale(vault_id, amount):
    try:
        # vault_id should be the customer vault ID returned when adding a vault entry
        payload = {
            'security_key': '{user.privateApiKey}',
            'type': 'sale',
            'customer_vault_id': vault_id,
            'amount': amount
        }
        
        response = requests.post(
            'https://secure.networkmerchants.com/api/transact.php',
            data=payload
        )
        
        response_data = dict(x.split('=') for x in response.text.split('&'))
        
        if response_data.get('response') == '1':
            print('Vault sale processed successfully')
            return {
                'transactionId': response_data.get('transactionid'),
                'authCode': response_data.get('authcode'),
                'responseText': response_data.get('responsetext')
            }
        else:
            raise Exception(response_data.get('responsetext', 'Failed to process vault sale'))
            
    except Exception as error:
        print(f'Error processing vault sale: {error}')
        raise error
# Process sale using vault token
import requests

def process_vault_sale(vault_id, amount):
    try:
        # vault_id should be the customer vault ID returned when adding a vault entry
        payload = {
            'security_key': '{user.privateApiKey}',
            'type': 'sale',
            'customer_vault_id': vault_id,
            'amount': amount
        }
        
        response = requests.post(
            'https://secure.networkmerchants.com/api/transact.php',
            data=payload
        )
        
        response_data = dict(x.split('=') for x in response.text.split('&'))
        
        if response_data.get('response') == '1':
            print('Vault sale processed successfully')
            return {
                'transactionId': response_data.get('transactionid'),
                'authCode': response_data.get('authcode'),
                'responseText': response_data.get('responsetext')
            }
        else:
            raise Exception(response_data.get('responsetext', 'Failed to process vault sale'))
            
    except Exception as error:
        print(f'Error processing vault sale: {error}')
        raise error
// Process sale using vault token
[HttpPost("vault-sale")]
public async Task<IActionResult> ProcessVaultSale([FromBody] VaultSaleRequest request)
{
    try
    {
        // customerVaultId should be the ID returned when adding a vault entry
        var formData = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("security_key", "{user.privateApiKey}"),
            new KeyValuePair<string, string>("type", "sale"),
            new KeyValuePair<string, string>("customer_vault_id", request.CustomerVaultId),
            new KeyValuePair<string, string>("amount", request.Amount.ToString())
        });
        
        var response = await _httpClient.PostAsync(
            "https://secure.networkmerchants.com/api/transact.php",
            formData
        );
        
        var responseContent = await response.Content.ReadAsStringAsync();
        var responseData = ParseQueryString(responseContent);
        
        if (responseData.ContainsKey("response") && responseData["response"] == "1")
        {
            return Ok(new
            {
                success = true,
                transactionId = responseData.GetValueOrDefault("transactionid"),
                authCode = responseData.GetValueOrDefault("authcode"),
                responseText = responseData.GetValueOrDefault("responsetext")
            });
        }
        else
        {
            return BadRequest(new
            {
                success = false,
                error = responseData.GetValueOrDefault("responsetext", "Failed to process vault sale")
            });
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, new
        {
            success = false,
            error = "An error occurred while processing vault sale"
        });
    }
}
<?php
// Process sale using vault token
function processVaultSale($vaultId, $amount) {
    try {
        // $vaultId should be the customer vault ID returned when adding a vault entry
        $payload = [
            'security_key' => '{user.privateApiKey}',
            'type' => 'sale',
            'customer_vault_id' => $vaultId,
            'amount' => $amount
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://secure.networkmerchants.com/api/transact.php');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        if ($response === false) {
            throw new Exception('cURL error occurred');
        }
        
        // Parse the response (NMI returns form-encoded data)
        parse_str($response, $responseData);
        
        if ($responseData['response'] === '1') {
            return [
                'success' => true,
                'transactionId' => $responseData['transactionid'],
                'authCode' => $responseData['authcode'],
                'responseText' => $responseData['responsetext']
            ];
        } else {
            return [
                'success' => false,
                'error' => $responseData['responsetext'] ?? 'Failed to process vault sale'
            ];
        }
        
    } catch (Exception $error) {
        error_log('Error processing vault sale: ' . $error->getMessage());
        return [
            'success' => false,
            'error' => 'An error occurred while processing vault sale'
        ];
    }
}

// Example usage
function handleVaultSale() {
    $result = processVaultSale('cust_12345', '10.00');
    
    if ($result['success']) {
        echo 'Vault sale processed successfully' . PHP_EOL;
        echo 'Transaction ID: ' . $result['transactionId'] . PHP_EOL;
        echo 'Auth Code: ' . $result['authCode'] . PHP_EOL;
        echo 'Response: ' . $result['responseText'] . PHP_EOL;
    } else {
        echo 'Error: ' . $result['error'] . PHP_EOL;
    }
}

// REST API endpoint example
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/vault-sale') {
    header('Content-Type: application/json');
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['customerVaultId']) || !isset($input['amount'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid JSON input or missing required fields']);
        exit;
    }
    
    $result = processVaultSale($input['customerVaultId'], $input['amount']);
    
    if ($result['success']) {
        http_response_code(200);
    } else {
        http_response_code(500);
    }
    
    echo json_encode($result);
}
?>
<?php
// app/Http/Controllers/TransactionController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Services\TransactionService;

class TransactionController extends Controller
{
    public function __construct(
        private TransactionService $transactionService
    ) {}

    /**
     * Process sale using vault token
     */
    public function processVaultSale(Request $request): JsonResponse
    {
        $request->validate([
            'customerVaultId' => 'required|string',
            'amount' => 'required|numeric|min:0.01'
        ]);

        try {
            $result = $this->transactionService->processVaultSale(
                $request->customerVaultId,
                $request->amount
            );

            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'transactionId' => $result['transactionId'],
                    'authCode' => $result['authCode'],
                    'responseText' => $result['responseText']
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'error' => $result['error']
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('Error processing vault sale: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'An error occurred while processing vault sale'
            ], 500);
        }
    }
}

// app/Services/TransactionService.php
namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class TransactionService
{
    public function processVaultSale(string $vaultId, float $amount): array
    {
        try {
            // $vaultId should be the customer vault ID returned when adding a vault entry
            $response = Http::asForm()->post('https://secure.networkmerchants.com/api/transact.php', [
                'security_key' => '{user.privateApiKey}',
                'type' => 'sale',
                'customer_vault_id' => $vaultId,
                'amount' => number_format($amount, 2, '.', '')
            ]);

            $responseData = $this->parseNmiResponse($response->body());

            if ($responseData['response'] === '1') {
                return [
                    'success' => true,
                    'transactionId' => $responseData['transactionid'],
                    'authCode' => $responseData['authcode'],
                    'responseText' => $responseData['responsetext']
                ];
            } else {
                return [
                    'success' => false,
                    'error' => $responseData['responsetext'] ?? 'Failed to process vault sale'
                ];
            }

        } catch (\Exception $e) {
            Log::error('Error processing vault sale: ' . $e->getMessage());
            return [
                'success' => false,
                'error' => 'An error occurred while processing vault sale'
            ];
        }
    }

    /**
     * Parse NMI's form-encoded response
     */
    private function parseNmiResponse(string $response): array
    {
        parse_str($response, $data);
        return $data;
    }
}