Refund a hosted payment
Track a full or partial refund against an existing paid payment.
Identify the original payment
Use the payment_id saved during hosted checkout. Create refund uses plugin authentication and the documented amount, currency, reason and merchant_refund_id. Do not refund more than the captured amount.
Keep a stable refund reference
Save the original refund request before sending it. The reviewed refund handler requires an Idempotency-Key of at least 16 characters on the first request and on retries. Reuse that key for the same refund. merchant_refund_id is optional, but useful for your own tracking. Confirm retention and changed-body behavior before automating retries.
Record the response
Retain refund_id, payment_id, provider_reference and the returned status. The source sample uses completed; it does not prove every refund completes synchronously. Reconcile ambiguous results with support rather than issuing another refund blindly.
Request example
Choose Node.js, Python, PHP, Ruby, Java or cURL. Run signed requests on your backend. PHP, Ruby and Java include signing directly. Java requires JDK 17 or newer.
Signing helpers: Node.js · Python. cURL shows the request shape; generate its signature first.
import { pluginSignedHeaders } from './plugin-signing.mjs';
const path = `/refunds/create`;
const query = '';
const payload = {
"merchant_id": "MERCHANT_001",
"payment_id": "pay_123",
"amount": "100.00",
"currency": "INR",
"reason": "Customer requested partial refund",
"merchant_refund_id": "refund_ORDER_123_1"
};
const body = JSON.stringify(payload);
const headers = pluginSignedHeaders({
method: 'POST', path, body,
keyId: process.env.ZYTEPE_API_KEY_ID,
secret: process.env.ZYTEPE_API_SECRET,
});
// Save this key before sending; reuse it for the same payment retry.
const idempotencyKey = process.env.ZYTEPE_IDEMPOTENCY_KEY;
if (!idempotencyKey || idempotencyKey.length < 16) throw new Error('Set a saved idempotency key of at least 16 characters');
headers['Idempotency-Key'] = idempotencyKey;
headers['Content-Type'] = 'application/json';
const url = 'https://api.zytepe.com' + path + (query ? '?' + query : '');
const response = await fetch(url, { method: 'POST', headers, body });
if (!response.ok) throw new Error('Request failed: HTTP ' + response.status);
const result = await response.json();
// Store the returned identifiers securely. Do not log customer data.import json, os
from urllib.parse import quote
from urllib.request import Request, urlopen
from zytepe_signing import plugin_signed_headers
path = f'/refunds/create'
query = ''
payload = json.loads('''{
"merchant_id": "MERCHANT_001",
"payment_id": "pay_123",
"amount": "100.00",
"currency": "INR",
"reason": "Customer requested partial refund",
"merchant_refund_id": "refund_ORDER_123_1"
}''')
body = json.dumps(payload, separators=(',', ':'), ensure_ascii=False)
headers = plugin_signed_headers(
method='POST', path=path, body=body,
key_id=os.environ['ZYTEPE_API_KEY_ID'],
secret=os.environ['ZYTEPE_API_SECRET'],
)
# Reuse the saved key for the same payment retry.
key = os.environ['ZYTEPE_IDEMPOTENCY_KEY']
if len(key) < 16: raise ValueError('Idempotency key must be at least 16 characters')
headers['Idempotency-Key'] = key
headers['Content-Type'] = 'application/json'
url = 'https://api.zytepe.com' + path + ('?' + query if query else '')
request = Request(url, method='POST', headers=headers, data=body.encode('utf-8'))
with urlopen(request, timeout=30) as response:
result = json.load(response)
# Store identifiers securely; handle HTTPError/URLError in your application.
# A timeout does not mean failure. Recover before creating another payment.<?php
// PHP 8+ with the cURL extension. Run on your server.
function envRequired(string $name): string {
$value = getenv($name);
if ($value === false || $value === '') throw new RuntimeException('Set ' . $name);
return $value;
}
$path = '/refunds/create';
$query = '';
$body = <<<'JSON'
{
"merchant_id": "MERCHANT_001",
"payment_id": "pay_123",
"amount": "100.00",
"currency": "INR",
"reason": "Customer requested partial refund",
"merchant_refund_id": "refund_ORDER_123_1"
}
JSON;
$headers = [];
$key = envRequired('ZYTEPE_API_KEY_ID');
$secret = envRequired('ZYTEPE_API_SECRET');
$timestamp = (string) time();
$canonical = $timestamp . '.POST.' . $path . '.' . $body;
$signature = hash_hmac('sha256', $canonical, $secret);
$headers = ["X-ZytePe-Api-Key: $key", "X-ZytePe-Timestamp: $timestamp", "X-ZytePe-Signature: $signature"];
// Save and reuse the same key for retries of this payment.
$retryKey = envRequired('ZYTEPE_IDEMPOTENCY_KEY');
if (strlen($retryKey) < 16) throw new RuntimeException('Idempotency key must be at least 16 characters');
$headers[] = 'Idempotency-Key: ' . $retryKey;
$headers[] = 'Content-Type: application/json';
$url = 'https://api.zytepe.com' . $path . ($query !== '' ? '?' . $query : '');
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30, CURLOPT_POSTFIELDS => $body]);
$response = curl_exec($ch);
if ($response === false) throw new RuntimeException(curl_error($ch));
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) throw new RuntimeException('HTTP ' . $status);
$result = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
// Store returned identifiers securely. Recover uncertain payments before retrying.require 'net/http'
require 'uri'
require 'json'
require 'openssl'
require 'securerandom'
path = '/refunds/create'
query = ''
body = <<~'JSON'.chomp
{
"merchant_id": "MERCHANT_001",
"payment_id": "pay_123",
"amount": "100.00",
"currency": "INR",
"reason": "Customer requested partial refund",
"merchant_refund_id": "refund_ORDER_123_1"
}
JSON
headers = {}
key = ENV.fetch('ZYTEPE_API_KEY_ID')
secret = ENV.fetch('ZYTEPE_API_SECRET')
timestamp = Time.now.to_i.to_s
canonical = [timestamp, 'POST', path, body].join('.')
signature = OpenSSL::HMAC.hexdigest('SHA256', secret, canonical)
headers = { 'X-ZytePe-Api-Key' => key, 'X-ZytePe-Timestamp' => timestamp,
'X-ZytePe-Signature' => signature }
# Save and reuse this key for retries of the same payment.
retry_key = ENV.fetch('ZYTEPE_IDEMPOTENCY_KEY')
raise 'Idempotency key must be at least 16 characters' if retry_key.length < 16
headers['Idempotency-Key'] = retry_key
headers['Content-Type'] = 'application/json'
uri = URI('https://api.zytepe.com' + path + (query.empty? ? '' : '?' + query))
request = Net::HTTP::Post.new(uri, headers)
request.body = body
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
http.request(request)
end
raise 'HTTP ' + response.code unless response.is_a?(Net::HTTPSuccess)
result = JSON.parse(response.body)
# Store returned identifiers securely. Recover uncertain payments before retrying.// Java 17+. Save as ZytePeExample.java and run on your server.
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class ZytePeExample {
private static String env(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) throw new IllegalArgumentException("Set " + name);
return value;
}
public static void main(String[] args) throws Exception {
String path = "/refunds/create";
String query = "";
String body = """
{
"merchant_id": "MERCHANT_001",
"payment_id": "pay_123",
"amount": "100.00",
"currency": "INR",
"reason": "Customer requested partial refund",
"merchant_refund_id": "refund_ORDER_123_1"
}
""".stripTrailing();
var request = HttpRequest.newBuilder(URI.create(
"https://api.zytepe.com" + path + (query.isEmpty() ? "" : "?" + query)))
.timeout(Duration.ofSeconds(30));
String key = env("ZYTEPE_API_KEY_ID");
String secret = env("ZYTEPE_API_SECRET");
String timestamp = Long.toString(Instant.now().getEpochSecond());
String canonical = timestamp + ".POST." + path + "." + body;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String signature = HexFormat.of().formatHex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));
request.header("X-ZytePe-Api-Key", key).header("X-ZytePe-Timestamp", timestamp)
.header("X-ZytePe-Signature", signature);
// Save this key before sending; reuse it for retries of the same payment.
String retryKey = env("ZYTEPE_IDEMPOTENCY_KEY");
if (retryKey.length() < 16) throw new IllegalArgumentException("Idempotency key must be at least 16 characters");
request.header("Idempotency-Key", retryKey);
request.header("Content-Type", "application/json");
request.method("POST", HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8));
var client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
var response = client.send(request.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() < 200 || response.statusCode() >= 300)
throw new IllegalStateException("HTTP " + response.statusCode());
String result = response.body(); // Parse JSON using your application's JSON library.
// Store identifiers securely. Recover uncertain payments before retrying.
}
}curl --request POST \
--url 'https://api.zytepe.com/refunds/create' \
--header 'X-ZytePe-Api-Key: <key-id>' \
--header 'X-ZytePe-Timestamp: <unix-seconds>' \
--header 'X-ZytePe-Signature: <signature>' \
--header 'Idempotency-Key: <saved-key-at-least-16-characters>' \
--header 'Content-Type: application/json' \
--data-binary @request.jsonRequest fields
Optional fields can be omitted. Conditional fields depend on the payment method. Labels reflect the reviewed API schemas and handler checks.
merchant_idRequiredYour merchant identifier.
payment_idRequiredThe payment identifier returned by checkout creation.
amountRequiredPayment amount in the documented currency.
currencyOptionalDefaults to INR.
reasonOptionalReason for the refund.
merchant_refund_idOptionalYour refund reference. Retain it for tracking.
Path, query and headers
Idempotency-KeyRequiredheaderRequired by the reviewed refund handler. At least 16 characters; reuse the saved key for the same refund retry.
Request body
{
"merchant_id": "MERCHANT_001",
"payment_id": "pay_123",
"amount": "100.00",
"currency": "INR",
"reason": "Customer requested partial refund",
"merchant_refund_id": "refund_ORDER_123_1"
}Example response
{
"refund_id": "refund_ORDER_123_1",
"payment_id": "pay_123",
"status": "completed",
"amount": "100.0000",
"currency": "INR",
"provider_reference": "RFND123456",
"merchant_refund_id": "refund_ORDER_123_1"
}Explore the business workflow: Payment gateway overview.
