Adding Customers to Vault
Add a new customer to the vault with their payment information by calling the NMI Payments API.
API Key Configuration Security Key You can find your API security key at key management under 'Merchant keys'.
This key is private and should be kept secure on your server. It authenticates your merchant account and authorizes vault operations.
Your sandbox key has been included in the code sample on the right.
Security: Never expose your API security key in client-side code. Always keep it secure on your server. While we have included your test key in the code sample, you should not commit it to source control and instead inject it via an environment variable.
Server-side Example
// Add customer to vault using payment token
const express = require('express');
const axios = require('axios');
const router = express.Router();
router.post('/add-to-vault', async (req, res) => {
try {
const { paymentToken, customerId, firstName, lastName, email } = req.body;
// Call NMI's v5 Customers API
const response = await axios.post('https://secure.nmi.com/api/v5/customers', {
payment_details: {
payment_token: paymentToken
},
billing_address: {
first_name: firstName,
last_name: lastName,
email: email
}
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': '{user.privateApiKey}'
}
});
// Check for successful response
if (response.data.id) {
return res.json({
success: true,
customerVaultId: response.data.id
});
} else {
return res.json({
success: false,
error: response.data.response_text || 'Failed to add customer to vault'
});
}
} catch (error) {
console.error('Error adding to vault:', error);
return res.status(500).json({
success: false,
error: 'An error occurred while adding to vault'
});
}
});
module.exports = router;# Add customer to vault using payment token
import requests
def add_to_vault(payment_token, customer_data):
try:
headers = {
'Content-Type': 'application/json',
'Authorization': '{user.privateApiKey}'
}
payload = {
'payment_details': {
'payment_token': payment_token
},
'billing_address': {
'first_name': customer_data['firstName'],
'last_name': customer_data['lastName'],
'email': customer_data['email']
}
}
response = requests.post(
'https://secure.nmi.com/api/v5/customers',
json=payload,
headers=headers
)
response_data = response.json()
if response_data.get('id'):
print('Customer added to vault successfully')
return response_data.get('id')
else:
raise Exception(response_data.get('response_text', 'Failed to add customer to vault'))
except Exception as error:
print(f'Error adding to vault: {error}')
raise error
# Example usage
def handle_add_to_vault():
customer_data = {
'customerId': 'cust_12345',
'firstName': 'John',
'lastName': 'Doe',
'email': '[email protected]'
}
# payment_token comes from your payment component
vault_id = add_to_vault(payment_token, customer_data)
print(f'Customer vault ID: {vault_id}')// Add customer to vault using payment token
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.HashMap;
@PostMapping("/add-to-vault")
public ResponseEntity<Map<String, Object>> addToVault(@RequestBody VaultRequest request) {
try {
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> paymentDetails = new HashMap<>();
paymentDetails.put("payment_token", request.getPaymentToken());
Map<String, Object> billingAddress = new HashMap<>();
billingAddress.put("first_name", request.getFirstName());
billingAddress.put("last_name", request.getLastName());
billingAddress.put("email", request.getEmail());
Map<String, Object> payload = new HashMap<>();
payload.put("payment_details", paymentDetails);
payload.put("billing_address", billingAddress);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "{user.privateApiKey}");
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
// Call NMI's v5 Customers API
ResponseEntity<Map> response = restTemplate.exchange(
"https://secure.nmi.com/api/v5/customers",
HttpMethod.POST,
entity,
Map.class
);
Map<String, Object> responseData = response.getBody();
Map<String, Object> result = new HashMap<>();
// Check for successful response
if (responseData.get("id") != null) {
result.put("success", true);
result.put("customerVaultId", responseData.get("id"));
} else {
result.put("success", false);
result.put("error", responseData.getOrDefault("response_text", "Failed to add customer to vault"));
}
return ResponseEntity.ok(result);
} catch (Exception error) {
System.err.println("Error adding to vault: " + error.getMessage());
Map<String, Object> errorResult = new HashMap<>();
errorResult.put("success", false);
errorResult.put("error", "An error occurred while adding to vault");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
}
}// Add customer to vault using payment token
using System.Text;
using System.Text.Json;
[HttpPost("add-to-vault")]
public async Task<IActionResult> AddToVault([FromBody] VaultRequest request)
{
try
{
var payload = new
{
payment_details = new
{
payment_token = request.PaymentToken
},
billing_address = new
{
first_name = request.FirstName,
last_name = request.LastName,
email = request.Email
}
};
var jsonContent = new StringContent(
JsonSerializer.Serialize(payload),
Encoding.UTF8,
"application/json"
);
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add("Authorization", "{user.privateApiKey}");
var response = await _httpClient.PostAsync(
"https://secure.nmi.com/api/v5/customers",
jsonContent
);
var responseContent = await response.Content.ReadAsStringAsync();
var responseData = JsonSerializer.Deserialize<Dictionary<string, object>>(responseContent);
if (responseData.TryGetValue("id", out var customerId) && customerId != null)
{
return Ok(new
{
success = true,
customerVaultId = customerId.ToString()
});
}
else
{
return BadRequest(new
{
success = false,
error = responseData.GetValueOrDefault("response_text")?.ToString() ?? "Failed to add customer to vault"
});
}
}
catch (Exception ex)
{
return StatusCode(500, new
{
success = false,
error = "An error occurred while adding to vault"
});
}
}<?php
// Add customer to vault using payment token
function addToVault($paymentToken, $customerData) {
try {
$payload = [
'payment_details' => [
'payment_token' => $paymentToken
],
'billing_address' => [
'first_name' => $customerData['firstName'],
'last_name' => $customerData['lastName'],
'email' => $customerData['email']
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://secure.nmi.com/api/v5/customers');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: {user.privateApiKey}'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false) {
throw new Exception('cURL error occurred');
}
// Parse the JSON response
$responseData = json_decode($response, true);
if (!empty($responseData['id'])) {
return [
'success' => true,
'customerVaultId' => $responseData['id']
];
} else {
return [
'success' => false,
'error' => $responseData['response_text'] ?? 'Failed to add customer to vault'
];
}
} catch (Exception $error) {
error_log('Error adding to vault: ' . $error->getMessage());
return [
'success' => false,
'error' => 'An error occurred while adding to vault'
];
}
}
// Example usage
function handleAddToVault() {
$customerData = [
'customerId' => 'cust_12345',
'firstName' => 'John',
'lastName' => 'Doe',
'email' => '[email protected]'
];
// $paymentToken comes from your payment component
$result = addToVault($paymentToken, $customerData);
if ($result['success']) {
echo 'Customer vault ID: ' . $result['customerVaultId'];
} else {
echo 'Error: ' . $result['error'];
}
}
// REST API endpoint example
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/add-to-vault') {
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'Invalid JSON input']);
exit;
}
$result = addToVault(
$input['paymentToken'],
[
'customerId' => $input['customerId'],
'firstName' => $input['firstName'],
'lastName' => $input['lastName'],
'email' => $input['email']
]
);
if ($result['success']) {
http_response_code(200);
} else {
http_response_code(500);
}
echo json_encode($result);
}
?><?php
// app/Http/Controllers/CustomerVaultController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class CustomerVaultController extends Controller
{
/**
* Add customer to vault
*/
public function addToVault(Request $request): JsonResponse
{
$request->validate([
'paymentToken' => 'required|string',
'firstName' => 'required|string',
'lastName' => 'required|string',
'email' => 'required|email'
]);
try {
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization' => '{user.privateApiKey}'
])->post('https://secure.nmi.com/api/v5/customers', [
'payment_details' => [
'payment_token' => $request->paymentToken
],
'billing_address' => [
'first_name' => $request->firstName,
'last_name' => $request->lastName,
'email' => $request->email
]
]);
$responseData = $response->json();
if (!empty($responseData['id'])) {
return response()->json([
'success' => true,
'customerVaultId' => $responseData['id']
]);
} else {
return response()->json([
'success' => false,
'error' => $responseData['response_text'] ?? 'Failed to add customer to vault'
], 400);
}
} catch (\Exception $e) {
Log::error('Error adding to vault: ' . $e->getMessage());
return response()->json([
'success' => false,
'error' => 'An error occurred while adding to vault'
], 500);
}
}
}Updated 3 months ago
