Managing Entries

Update existing customer information and delete entries as needed.

📘

All vault operations require the customer_id to identify the specific customer record.

Updating Customer

The following is an example code snippet for updating an existing customer. Full parameter support can be seen in the API Reference under the "Update Customer" request.

Server-side Example

// Update customer in vault
const axios = require('axios');

router.put('/update-vault/:customerId', async (req, res) => {
  try {
    const { customerId } = req.params;
    const { paymentToken, billingData, shippingData } = req.body;
    
    const response = await axios.put(`https://secure.nmi.com/api/v5/customers/${customerId}`, {
      payment_details: {
        payment_token: paymentToken
      },
      billing_address: {
        first_name: billingData.firstName,
        last_name: billingData.lastName,
        address1: billingData.address1,
        city: billingData.city,
        state: billingData.state,
        zip: billingData.zip,
        country: billingData.country,
        phone: billingData.phone,
        email: billingData.email,
        company: billingData.company
      },
      shipping_address: {
        first_name: shippingData.firstName,
        last_name: shippingData.lastName,
        address1: shippingData.address1,
        city: shippingData.city,
        state: shippingData.state,
        zip: shippingData.zip,
        country: shippingData.country,
        phone: shippingData.phone,
        email: shippingData.email,
        company: shippingData.company
      }
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': '{user.privateApiKey}'
      }
    });
    
    if (response.data.id) {
      return res.json({ success: true });
    } else {
      return res.json({
        success: false,
        error: response.data.response_text
      });
    }
  } catch (error) {
    console.error('Error updating vault:', error);
    return res.status(500).json({
      success: false,
      error: 'An error occurred while updating vault'
    });
  }
});
# Update customer in vault
import requests

def update_vault_entry(vault_id, payment_token, billing_data, shipping_data):
    try:
        headers = {
            'Content-Type': 'application/json',
            'Authorization': '{user.privateApiKey}'
        }
        
        payload = {
            'payment_details': {
                'payment_token': payment_token
            },
            'billing_address': {
                'first_name': billing_data['firstName'],
                'last_name': billing_data['lastName'],
                'address1': billing_data['address1'],
                'city': billing_data['city'],
                'state': billing_data['state'],
                'zip': billing_data['zip'],
                'country': billing_data['country'],
                'phone': billing_data['phone'],
                'email': billing_data['email'],
                'company': billing_data['company']
            },
            'shipping_address': {
                'first_name': shipping_data['firstName'],
                'last_name': shipping_data['lastName'],
                'address1': shipping_data['address1'],
                'city': shipping_data['city'],
                'state': shipping_data['state'],
                'zip': shipping_data['zip'],
                'country': shipping_data['country'],
                'phone': shipping_data['phone'],
                'email': shipping_data['email'],
                'company': shipping_data['company']
            }
        }
        
        response = requests.put(
            f'https://secure.nmi.com/api/v5/customers/{vault_id}',
            json=payload,
            headers=headers
        )
        
        response_data = response.json()
        
        if response_data.get('id'):
            print('Customer updated in vault successfully')
            return True
        else:
            raise Exception(response_data.get('response_text', 'Failed to update customer'))
            
    except Exception as error:
        print(f'Error updating vault: {error}')
        raise error
// Update customer in vault
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.HashMap;

@PutMapping("/update-vault/{customerId}")
public ResponseEntity<Map<String, Object>> updateVaultEntry(
    @PathVariable String customerId,
    @RequestBody UpdateVaultRequest 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.getBillingData().getFirstName());
        billingAddress.put("last_name", request.getBillingData().getLastName());
        billingAddress.put("address1", request.getBillingData().getAddress1());
        billingAddress.put("city", request.getBillingData().getCity());
        billingAddress.put("state", request.getBillingData().getState());
        billingAddress.put("zip", request.getBillingData().getZip());
        billingAddress.put("country", request.getBillingData().getCountry());
        billingAddress.put("phone", request.getBillingData().getPhone());
        billingAddress.put("email", request.getBillingData().getEmail());
        billingAddress.put("company", request.getBillingData().getCompany());
        
        Map<String, Object> shippingAddress = new HashMap<>();
        shippingAddress.put("first_name", request.getShippingData().getFirstName());
        shippingAddress.put("last_name", request.getShippingData().getLastName());
        shippingAddress.put("address1", request.getShippingData().getAddress1());
        shippingAddress.put("city", request.getShippingData().getCity());
        shippingAddress.put("state", request.getShippingData().getState());
        shippingAddress.put("zip", request.getShippingData().getZip());
        shippingAddress.put("country", request.getShippingData().getCountry());
        shippingAddress.put("phone", request.getShippingData().getPhone());
        shippingAddress.put("email", request.getShippingData().getEmail());
        shippingAddress.put("company", request.getShippingData().getCompany());
        
        Map<String, Object> payload = new HashMap<>();
        payload.put("payment_details", paymentDetails);
        payload.put("billing_address", billingAddress);
        payload.put("shipping_address", shippingAddress);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "{user.privateApiKey}");
        
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
        
        ResponseEntity<Map> response = restTemplate.exchange(
            "https://secure.nmi.com/api/v5/customers/" + customerId,
            HttpMethod.PUT,
            entity,
            Map.class
        );
        
        Map<String, Object> responseData = response.getBody();
        Map<String, Object> result = new HashMap<>();
        
        if (responseData.get("id") != null) {
            result.put("success", true);
        } else {
            result.put("success", false);
            result.put("error", responseData.getOrDefault("response_text", "Failed to update customer"));
        }
        
        return ResponseEntity.ok(result);
        
    } catch (Exception error) {
        System.err.println("Error updating vault: " + error.getMessage());
        
        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("success", false);
        errorResult.put("error", "An error occurred while updating vault");
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }
}
// Update customer in vault
using System.Text;
using System.Text.Json;

[HttpPut("update-vault/{customerId}")]
public async Task<IActionResult> UpdateVaultEntry(string customerId, [FromBody] UpdateVaultRequest request)
{
    try
    {
        var payload = new
        {
            payment_details = new
            {
                payment_token = request.PaymentToken
            },
            billing_address = new
            {
                first_name = request.BillingData.FirstName,
                last_name = request.BillingData.LastName,
                address1 = request.BillingData.Address1,
                city = request.BillingData.City,
                state = request.BillingData.State,
                zip = request.BillingData.Zip,
                country = request.BillingData.Country,
                phone = request.BillingData.Phone,
                email = request.BillingData.Email,
                company = request.BillingData.Company
            },
            shipping_address = new
            {
                first_name = request.ShippingData.FirstName,
                last_name = request.ShippingData.LastName,
                address1 = request.ShippingData.Address1,
                city = request.ShippingData.City,
                state = request.ShippingData.State,
                zip = request.ShippingData.Zip,
                country = request.ShippingData.Country,
                phone = request.ShippingData.Phone,
                email = request.ShippingData.Email,
                company = request.ShippingData.Company
            }
        };

        var jsonContent = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json"
        );

        _httpClient.DefaultRequestHeaders.Clear();
        _httpClient.DefaultRequestHeaders.Add("Authorization", "{user.privateApiKey}");

        var response = await _httpClient.PutAsync(
            $"https://secure.nmi.com/api/v5/customers/{customerId}",
            jsonContent
        );
        
        var responseContent = await response.Content.ReadAsStringAsync();
        var responseData = JsonSerializer.Deserialize<Dictionary<string, object>>(responseContent);
        
        if (responseData.TryGetValue("id", out var id) && id != null)
        {
            return Ok(new { success = true });
        }
        else
        {
            return BadRequest(new
            {
                success = false,
                error = responseData.GetValueOrDefault("response_text")?.ToString() ?? "Failed to update customer"
            });
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, new
        {
            success = false,
            error = "An error occurred while updating vault"
        });
    }
}
<?php
// Update customer in vault
function updateVaultEntry($vaultId, $paymentToken, $billingData, $shippingData) {
    try {
        $payload = [
            'payment_details' => [
                'payment_token' => $paymentToken
            ],
            'billing_address' => [
                'first_name' => $billingData['firstName'],
                'last_name' => $billingData['lastName'],
                'address1' => $billingData['address1'],
                'city' => $billingData['city'],
                'state' => $billingData['state'],
                'zip' => $billingData['zip'],
                'country' => $billingData['country'],
                'phone' => $billingData['phone'],
                'email' => $billingData['email'],
                'company' => $billingData['company']
            ],
            'shipping_address' => [
                'first_name' => $shippingData['firstName'],
                'last_name' => $shippingData['lastName'],
                'address1' => $shippingData['address1'],
                'city' => $shippingData['city'],
                'state' => $shippingData['state'],
                'zip' => $shippingData['zip'],
                'country' => $shippingData['country'],
                'phone' => $shippingData['phone'],
                'email' => $shippingData['email'],
                'company' => $shippingData['company']
            ]
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://secure.nmi.com/api/v5/customers/' . $vaultId);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        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);
        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];
        } else {
            return [
                'success' => false,
                'error' => $responseData['response_text'] ?? 'Failed to update customer'
            ];
        }
        
    } catch (Exception $error) {
        error_log('Error updating vault: ' . $error->getMessage());
        return [
            'success' => false,
            'error' => 'An error occurred while updating vault'
        ];
    }
}

// Example usage
function handleUpdateVault() {
    $billingData = [
        'firstName' => 'John',
        'lastName' => 'Doe',
        'address1' => '123 Main St',
        'city' => 'Anytown',
        'state' => 'CA',
        'zip' => '12345',
        'country' => 'US',
        'phone' => '555-123-4567',
        'email' => '[email protected]',
        'company' => 'Acme Corp'
    ];
    
    $shippingData = [
        'firstName' => 'John',
        'lastName' => 'Doe',
        'address1' => '456 Oak Ave',
        'city' => 'Somewhere',
        'state' => 'CA',
        'zip' => '54321',
        'country' => 'US',
        'phone' => '555-987-6543',
        'email' => '[email protected]',
        'company' => 'Acme Corp'
    ];
    
    $result = updateVaultEntry('cust_12345', $paymentToken, $billingData, $shippingData);
    
    if ($result['success']) {
        echo 'Customer updated in vault successfully';
    } else {
        echo 'Error: ' . $result['error'];
    }
}

// REST API endpoint example
if ($_SERVER['REQUEST_METHOD'] === 'PUT' && preg_match('/\/update-vault\/(.+)/', $_SERVER['REQUEST_URI'], $matches)) {
    header('Content-Type: application/json');
    
    $customerId = $matches[1];
    $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 = updateVaultEntry(
        $customerId,
        $input['paymentToken'],
        $input['billingData'],
        $input['shippingData']
    );
    
    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
{
    /**
     * Update customer in vault
     */
    public function updateVault(Request $request, string $customerId): JsonResponse
    {
        $request->validate([
            'paymentToken' => 'required|string',
            'billingData' => 'required|array',
            'billingData.firstName' => 'required|string',
            'billingData.lastName' => 'required|string',
            'billingData.address1' => 'required|string',
            'billingData.city' => 'required|string',
            'billingData.state' => 'required|string',
            'billingData.zip' => 'required|string',
            'billingData.country' => 'required|string',
            'billingData.phone' => 'required|string',
            'billingData.email' => 'required|email',
            'billingData.company' => 'nullable|string',
            'shippingData' => 'required|array',
            'shippingData.firstName' => 'required|string',
            'shippingData.lastName' => 'required|string',
            'shippingData.address1' => 'required|string',
            'shippingData.city' => 'required|string',
            'shippingData.state' => 'required|string',
            'shippingData.zip' => 'required|string',
            'shippingData.country' => 'required|string',
            'shippingData.phone' => 'required|string',
            'shippingData.email' => 'required|email',
            'shippingData.company' => 'nullable|string'
        ]);

        try {
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => '{user.privateApiKey}'
            ])->put("https://secure.nmi.com/api/v5/customers/{$customerId}", [
                'payment_details' => [
                    'payment_token' => $request->paymentToken
                ],
                'billing_address' => [
                    'first_name' => $request->billingData['firstName'],
                    'last_name' => $request->billingData['lastName'],
                    'address1' => $request->billingData['address1'],
                    'city' => $request->billingData['city'],
                    'state' => $request->billingData['state'],
                    'zip' => $request->billingData['zip'],
                    'country' => $request->billingData['country'],
                    'phone' => $request->billingData['phone'],
                    'email' => $request->billingData['email'],
                    'company' => $request->billingData['company'] ?? ''
                ],
                'shipping_address' => [
                    'first_name' => $request->shippingData['firstName'],
                    'last_name' => $request->shippingData['lastName'],
                    'address1' => $request->shippingData['address1'],
                    'city' => $request->shippingData['city'],
                    'state' => $request->shippingData['state'],
                    'zip' => $request->shippingData['zip'],
                    'country' => $request->shippingData['country'],
                    'phone' => $request->shippingData['phone'],
                    'email' => $request->shippingData['email'],
                    'company' => $request->shippingData['company'] ?? ''
                ]
            ]);

            $responseData = $response->json();

            if (!empty($responseData['id'])) {
                return response()->json(['success' => true]);
            } else {
                return response()->json([
                    'success' => false,
                    'error' => $responseData['response_text'] ?? 'Failed to update customer'
                ], 400);
            }

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

Deleting Customer

The following example shows all required parameters for deleting a customer from the vault. For additional reference, see the "Delete Customer" in our API documentation.

Server-side Example

// Delete customer from vault
const axios = require('axios');

router.delete('/delete-vault/:customerId', async (req, res) => {
  try {
    const { customerId } = req.params;
    
    const response = await axios.delete(`https://secure.nmi.com/api/v5/customers/${customerId}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': '{user.privateApiKey}'
      }
    });
    
    return res.json({ success: true });
  } catch (error) {
    console.error('Error deleting from vault:', error);
    return res.status(500).json({
      success: false,
      error: 'An error occurred while deleting from vault'
    });
  }
});
# Delete customer from vault
import requests

def delete_vault_entry(vault_id):
    try:
        headers = {
            'Content-Type': 'application/json',
            'Authorization': '{user.privateApiKey}'
        }
        
        response = requests.delete(
            f'https://secure.nmi.com/api/v5/customers/{vault_id}',
            headers=headers
        )
        
        if response.status_code == 200:
            print('Customer deleted from vault successfully')
            return True
        else:
            response_data = response.json()
            raise Exception(response_data.get('response_text', 'Failed to delete customer'))
            
    except Exception as error:
        print(f'Error deleting from vault: {error}')
        raise error
// Delete customer from vault
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.HashMap;

@DeleteMapping("/delete-vault/{customerId}")
public ResponseEntity<Map<String, Object>> deleteVaultEntry(@PathVariable String customerId) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "{user.privateApiKey}");
        
        HttpEntity<String> entity = new HttpEntity<>(headers);
        
        ResponseEntity<Map> response = restTemplate.exchange(
            "https://secure.nmi.com/api/v5/customers/" + customerId,
            HttpMethod.DELETE,
            entity,
            Map.class
        );
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        
        return ResponseEntity.ok(result);
        
    } catch (Exception error) {
        System.err.println("Error deleting from vault: " + error.getMessage());
        
        Map<String, Object> errorResult = new HashMap<>();
        errorResult.put("success", false);
        errorResult.put("error", "An error occurred while deleting from vault");
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }
}
// Delete customer from vault
[HttpDelete("delete-vault/{customerId}")]
public async Task<IActionResult> DeleteVaultEntry(string customerId)
{
    try
    {
        _httpClient.DefaultRequestHeaders.Clear();
        _httpClient.DefaultRequestHeaders.Add("Authorization", "{user.privateApiKey}");

        var response = await _httpClient.DeleteAsync(
            $"https://secure.nmi.com/api/v5/customers/{customerId}"
        );
        
        if (response.IsSuccessStatusCode)
        {
            return Ok(new { success = true });
        }
        else
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            var responseData = JsonSerializer.Deserialize<Dictionary<string, object>>(responseContent);
            
            return BadRequest(new
            {
                success = false,
                error = responseData?.GetValueOrDefault("response_text")?.ToString() ?? "Failed to delete customer"
            });
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, new
        {
            success = false,
            error = "An error occurred while deleting from vault"
        });
    }
}
<?php
// Delete customer from vault
function deleteVaultEntry($vaultId) {
    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://secure.nmi.com/api/v5/customers/' . $vaultId);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        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');
        }
        
        if ($httpCode === 200) {
            return ['success' => true];
        } else {
            $responseData = json_decode($response, true);
            return [
                'success' => false,
                'error' => $responseData['response_text'] ?? 'Failed to delete customer'
            ];
        }
        
    } catch (Exception $error) {
        error_log('Error deleting from vault: ' . $error->getMessage());
        return [
            'success' => false,
            'error' => 'An error occurred while deleting from vault'
        ];
    }
}

// Example usage
function handleDeleteVault() {
    $result = deleteVaultEntry('cust_12345');
    
    if ($result['success']) {
        echo 'Customer deleted from vault successfully';
    } else {
        echo 'Error: ' . $result['error'];
    }
}

// REST API endpoint example
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && preg_match('/\/delete-vault\/(.+)/', $_SERVER['REQUEST_URI'], $matches)) {
    header('Content-Type: application/json');
    
    $customerId = $matches[1];
    $result = deleteVaultEntry($customerId);
    
    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
{
    /**
     * Delete customer from vault
     */
    public function deleteVault(string $customerId): JsonResponse
    {
        try {
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => config('services.nmi.security_key')
            ])->delete("https://secure.nmi.com/api/v5/customers/{$customerId}");

            if ($response->successful()) {
                return response()->json(['success' => true]);
            } else {
                $responseData = $response->json();
                return response()->json([
                    'success' => false,
                    'error' => $responseData['response_text'] ?? 'Failed to delete customer'
                ], 400);
            }

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