Example of a signature
How to generate signatures?
Security
All the communication against and from our API will be signed and the signature must be included as header. This signature allows us to certificate data integrity within the communication.
Prerequisites
String platformId = "your-platform-id";
String secret = "your-api-key";
JSONObject body = new JSONObject();
body.put("orderId", "your-transaction-identifier");
body.put("paymentId", "90");
body.put("amount", "100.00");
body.put("platformId", platformId);platformId = 'your-platform-id'
secret = 'your-api-key'
body = {
"orderId": "your-transaction-identifier",
"paymentId": "90",
"amount": "100.00",
"platformId": platformId
}$platformId = 'your-platform-id';
$secret = 'your-api-key';
$body = [
"orderId" => "your-transaction-identifier",
"paymentId" => "90",
"amount" => "100.00",
"platformId" => $platformId
];const platformId = "your-platform-id";
const secret = "your-api-key";
const body = {
orderId: "your-transaction-identifier",
paymentId: "90",
amount: "100.00",
platformId: platformId,
};
int platformId = 0;
string secret = "000000-000000-000000-000000-000000";
var body = new
{
orderId = "d2671b51-b04d-444e-a2ab-306b4bc95038_87",
amount = "10.00",
symbol = "USD",
type = 1,
returnUrl = "https://localhost:7158/de/customer/paymentpending?paymentId=87",
platformId = 0
};Note: The previous body is an example, since it is dynamic and the signature can change according to the body of the request or response.
Step 1 - Create signature.
...
ObjectMapper objectMapper = new ObjectMapper();
String bodyJson = objectMapper.writeValueAsString(body);
String signatureContract = platformId + ";" + bodyJson + ";" + secret;
String signature = generateSignature(signatureContract, secret);
...
// Helper function to generate HMAC-SHA256 signature
private String generateSignature(String signatureContract, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256HMAC.init(secretKey);
byte[] hash = sha256HMAC.doFinal(signatureContract.getBytes(StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
for (byte b : hash) {
result.append(String.format("%02x", b));
}
return result.toString();
}
serialized_body = json.dumps(body, separators=(',', ':'), ensure_ascii=False)
signature_contract = f"{platform_id};{serialized_body};{secret}"
signature = hmac.new(secret.encode(), signature_contract.encode(), hashlib.sha256).hexdigest()$signatureContract = $platformId .";". json_encode($body) .";". $secret;
$signature = hash_hmac('sha256', $signatureContract, $secret);const serializedBody = JSON.stringify(body).replace(///g, "\/");
const signatureContract = ${platformId};${serializedBody};${secret};
const signature = crypto.createHmac("sha256", secret).update(signatureContract).digest("hex");string jsonBody = JsonSerializer.Serialize(body);
string jsonBodyFixed = jsonBody.Replace("/", "\\/");
string signatureContract = $"{platformId};{jsonBodyFixed};{secret}";
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(signatureContract));
string signature = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Step 2 - Execution of the Request
String signature = "your-signature"; // Replace with the generated signature
// Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000); // 10 seconds timeout
conn.setReadTimeout(10000);
conn.setDoOutput(true); // Allow sending data
// Set headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("x-signature", signature);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Get response code
int responseCode = conn.getResponseCode();
// Read the response
BufferedReader br;
if (responseCode == HttpURLConnection.HTTP_OK) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8));
}
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
// Close connection
conn.disconnect();
// Parse JSON response (if needed)
Map<String, Object> result = objectMapper.readValue(response.toString(), Map.class);
// Print result
System.out.println(result);import json
import requests
body_json = json.dumps(body)
headers = {
'Content-Type': 'application/json',
'x-signature': 'your_signature', # Replace with the actual signature
}
# Send the POST request
url = 'https://api.passimpay.io/v2/currencies'
try:
response = requests.post(url, headers=headers, data=body_json, timeout=10)
# Get the HTTP status code
http_code = response.status_code
# Parse the JSON response
result = response.json()
print(f'Response: {result}')
except requests.exceptions.RequestException as e:
print(f'An error occurred: {e}')$body = json_encode($body);
$headers = [
'Content-Type: application/json',
'x-signature: ' . $signature,
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'https://api.passimpay.io/v2/currencies');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$result = json_decode($result, true);
print_r($result);try {
const response = await axios({
method: "POST",
url: "https://api.passimpay.io/v2/currencies",
headers: {
"Content-Type": "application/json",
'x-signature': signature
},
data: body,
});
console.log(response.data);
} catch (error: any) {
console.error(error);
}using var httpClient = new HttpClient();
try
{
httpClient.DefaultRequestHeaders.Add("x-signature", signature);
httpClient.Timeout = TimeSpan.FromSeconds(10);
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync("https://api.passimpay.io/v2/currencies", content);
int httpCode = (int)response.StatusCode;
string resultContent = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<object>(resultContent);
Console.WriteLine($"HTTP Code: {httpCode}");
Console.WriteLine("Response:");
Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Signature use cases:
When you call us, you should send the
x-signatureheader, so we can validate the payload data integrity.When you receive a response, you must validate the
x-signatureheader presence and validate that it is valid.When you receive a callback, you must validate the
x-signatureheader presence and validate that it is valid.
Postman create signature Pre-request Script:
const crypto = require('crypto-js');
try {
const platformId = 0;
const secret = '000000-000000-000000-000000-000000';
if (!platformId || !secret) {
throw new Error('Missing required environment variables: platform_id or api_secret');
}
const requestBody = pm.request.body.raw;
let bodyJson;
if (requestBody) {
try {
bodyJson = JSON.parse(requestBody);
} catch (e) {
throw new Error('Invalid JSON in request body');
}
} else {
bodyJson = {};
}
const signatureContract = `${platformId};${JSON.stringify(bodyJson).replace(/\//g, "\\/")};${secret}`;
const signature = crypto.HmacSHA256(signatureContract, secret).toString();
pm.request.headers.add({
key: 'x-signature',
value: signature
});
} catch (error) {
console.error('Error in pre-request script:', error.message);
pm.environment.set('signature_error', error.message);
}
Last updated