Developer Integration Guide

Complete guide for integrating the Nexzoneo Payment API

Nexzoneo Payment API - Complete Developer Integration Guide

Table of Contents

Best Practices

Security

1. Never expose API credentials in client-side code

2. Always validate webhook signatures before processing

3. Use HTTPS for all URLs in production

4. Implement proper access controls for your webhook endpoints

5. Log security events for monitoring

Performance

1. Cache site settings to reduce API calls

2. Implement request timeouts (recommended: 30 seconds)

3. Use appropriate retry strategies with exponential backoff

4. Monitor API response times and error rates

User Experience

1. Redirect users promptly to payment URLs

2. Handle all payment outcomes (success, failure, cancel)

3. Provide clear error messages to users

4. Implement loading states during API calls

5. Send confirmation emails after successful payments

Development

1. Use test mode during development

2. Validate input data before API calls

3. Implement proper error handling and logging

4. Test webhook endpoints thoroughly

5. Monitor for duplicate payments using order IDs

Integration Examples

PHP Example

`php class Nexzoneoment {

private $siteKey;

private $securityToken;

private $baseUrl = 'https://nexzoneo.com/api/merchant/';

public function __construct($siteKey, $securityToken) {

$this->siteKey = $siteKey;

$this->securityToken = $securityToken;

}

public function createPaymentSession($orderData) {

$url = $this->baseUrl . 'create_payment_session';

$headers = [

'Content-Type: application/json',

'X-Site-Key: ' . $this->siteKey,

'Authorization: ' . $this->securityToken

];

$ch = curl_init($url);

curl_setopt_array($ch, [

CURLOPT_POST => true,

CURLOPT_POSTFIELDS => json_encode($orderData),

CURLOPT_HTTPHEADER => $headers,

CURLOPT_RETURNTRANSFER => true,

CURLOPT_SSL_VERIFYPEER => true,

CURLOPT_TIMEOUT => 30

]);

$response = curl_exec($ch);

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpCode === 200) {

return json_decode($response, true);

} else {

throw new Exception('API Error: ' . $response);

}

}

public function getSession($token) {

$url = $this->baseUrl . 'get_session?token=' . urlencode($token);

$headers = [

'X-Site-Key: ' . $this->siteKey,

'Authorization: ' . $this->securityToken

];

$ch = curl_init($url);

curl_setopt_array($ch, [

CURLOPT_HTTPHEADER => $headers,

CURLOPT_RETURNTRANSFER => true,

CURLOPT_SSL_VERIFYPEER => true,

CURLOPT_TIMEOUT => 30

]);

$response = curl_exec($ch);

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpCode === 200) {

return json_decode($response, true);

} else {

throw new Exception('API Error: ' . $response);

}

}

public function verifyWebhook($postData, $signature) {

$data = $postData;

unset($data['signature']);

ksort($data);

$expectedSignature = hash_hmac('sha256', json_encode($data), $this->securityToken);

return hash_equals($expectedSignature, $signature);

}

}

// Usage Example

try {

$nexzoneo = new NexzoneoPayment(

$_ENV['NEXZONEO_SITE_KEY'],

$_ENV['NEXZONEO_SECURITY_TOKEN']

);

$orderData = [

'order_id' => 'ORDER-' . time(),

'total' => 29.99,

'currency' => 'USD',

'customer_email' => 'customer@example.com',

'items' => [

[

'name' => 'Premium Plan',

'quantity' => 1,

'unit_price' => 29.99

]

]

];

$result = $nexzoneo->createPaymentSession($orderData);

if ($result['status'] === 'success') {

header('Location: ' . $result['data']['payment_url']);

exit;

} else {

throw new Exception('Payment session creation failed');

}

} catch (Exception $e) {

error_log('Payment error: ' . $e->getMessage());

// Show user-friendly error message

}

?>

`

Node.js Example

`javascript

const express = require("express");

const fetch = require("node-fetch");

const crypto = require("crypto");

class Nexzoneoment {

constructor(siteKey, securityToken) {

this.siteKey = siteKey;

this.securityToken = securityToken;

this.baseUrl = "https://nexzoneo.com/api/merchant/";

}

async createPaymentSession(orderData) {

const response = await fetch(this.baseUrl + "create_payment_session", {

method: "POST",

headers: {

"Content-Type": "application/json",

"X-Site-Key": this.siteKey,

Authorization: this.securityToken,

},

body: JSON.stringify(orderData),

timeout: 30000,

});

const result = await response.json();

if (!response.ok) {

throw new Error(API Error: ${result.data?.error "Unknown error"});

}

return result;

}

async getSession(token) {

const response = await fetch(

this.baseUrl + get_session?token=${encodeURIComponent(token)},

{

headers: {

"X-Site-Key": this.siteKey,

Authorization: this.securityToken,

},

timeout: 30000,

}

);

const result = await response.json();

if (!response.ok) {

throw new Error(API Error: ${result.data?.error "Unknown error"});

}

return result;

}

verifyWebhook(postData, signature) {

const data = { ...postData };

delete data.signature;

const sortedKeys = Object.keys(data).sort();

const sortedData = {};

sortedKeys.forEach((key) => {

sortedData[key] = data[key];

});

const expectedSignature = crypto

.createHmac("sha256", this.securityToken)

.update(JSON.stringify(sortedData))

.digest("hex");

return crypto.timingSafeEqual(

Buffer.from(signature, "hex"),

Buffer.from(expectedSignature, "hex")

);

}

}

// Express.js integration

const app = express();

app.use(express.json());

const nexzoneo = new NexzoneoPayment(

process.env.NEXZONEO_SITE_KEY,

process.env.NEXZONEO_SECURITY_TOKEN

);

app.post("/create-payment", async (req, res) => {

try {

const orderData = {

order_id: ORDER-${Date.now()},

total: req.body.amount,

currency: req.body.currency "USD",

customer_email: req.body.email,

items: req.body.items [],

};

const result = await nexzoneo.createPaymentSession(orderData);

res.json(result.data);

} catch (error) {

console.error("Payment creation error:", error.message);

res.status(500).json({ error: "Payment creation failed" });

}

});

app.post("/webhook", async (req, res) => {

try {

const isValid = nexzoneo.verifyWebhook(req.body, req.body.signature);

if (!isValid) {

console.error("Invalid webhook signature");

return res.status(400).send("Invalid signature");

}

// Process the webhook

const { order_id, payment_status } = req.body;

console.log(Payment ${order_id} status: ${payment_status});

// Update your database here

// Send confirmation emails

res.status(200).send("OK");

} catch (error) {

console.error("Webhook processing error:", error.message);

res.status(500).send("Error processing webhook");

}

});

`

Python Example

`python

import requests

import hmac

import hashlib

import json

from typing import Dict, Any

class Nexzoneoment:

def __init__(self, site_key: str, security_token: str):

self.site_key = site_key

self.security_token = security_token

self.base_url = 'https://nexzoneo.com/api/merchant/'

def create_payment_session(self, order_data: Dict[str, Any]) -> Dict[str, Any]:

url = self.base_url + 'create_payment_session'

headers = {

'Content-Type': 'application/json',

'X-Site-Key': self.site_key,

'Authorization': self.security_token

}

response = requests.post(

url,

headers=headers,

json=order_data,

timeout=30

)

result = response.json()

if response.status_code != 200:

raise Exception(f'API Error: {result.get("data", {}).get("error", "Unknown error")}')

return result

def get_session(self, token: str) -> Dict[str, Any]:

url = f'{self.base_url}get_session?token={token}'

headers = {

'X-Site-Key': self.site_key,

'Authorization': self.security_token

}

response = requests.get(url, headers=headers, timeout=30)

result = response.json()

if response.status_code != 200:

raise Exception(f'API Error: {result.get("data", {}).get("error", "Unknown error")}')

return result

def verify_webhook(self, post_data: Dict[str, Any], signature: str) -> bool:

data = post_data.copy()

data.pop('signature', None)

# Sort the data

sorted_data = {k: data[k] for k in sorted(data.keys())}

expected_signature = hmac.new(

self.security_token.encode(),

json.dumps(sorted_data, separators=(',', ':')).encode(),

hashlib.sha256

).hexdigest()

return hmac.compare_digest(expected_signature, signature)

Usage example

import os

from datetime import datetime

nexzoneo = NexzoneoPayment(

os.getenv('NEXZONEO_SITE_KEY'),

os.getenv('NEXZONEO_SECURITY_TOKEN')

)

try:

order_data = {

'order_id': f'ORDER-{int(datetime.now().timestamp())}',

'total': 29.99,

'currency': 'USD',

'customer_email': 'customer@example.com',

'items': [

{

'name': 'Premium Plan',

'quantity': 1,

'unit_price': 29.99

}

]

}

result = nexzoneo.create_payment_session(order_data)

if result['status'] == 'success':

payment_url = result['data']['payment_url']

print(f'Redirect user to: {payment_url}')

else:

raise Exception('Payment session creation failed')

except Exception as e:

print(f'Error: {e}')

``

---

This guide covers all aspects of using the Nexzoneo Pay API effectively. For additional support or questions, please contact our developer support team.

Need help? Contact Support