# 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

{% tabs %}
{% tab title="Java" %}

```java
Integer platformId = "50"; //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", 50); //your platform ID
```

{% endtab %}

{% tab title="Python" %}

```python
platformId = 50 # your platform ID
secret = 'your-api-key'
body = {
    "orderId": "your-transaction-identifier",
    "paymentId": 90,
    "amount": "100.00",
    "platformId": 50 # your platform ID
}
```

{% endtab %}

{% tab title="PHP" %}

```php
$platformId = 50; //your platform ID
$secret = 'your-api-key';
$body = [
    "orderId" => "your-transaction-identifier",
    "paymentId" => 90,
    "amount" => "100.00",
    "platformId" => $platformId //your platform ID
];
```

{% endtab %}

{% tab title="JS" %}

```
const platformId = 50; //your platform ID
const secret = "your-api-key";
const body = {
  orderId: "your-transaction-identifier",
  paymentId: 90,
  amount: "100.00",
  platformId: 50, //your platform ID
};

```

<br>
{% endtab %}

{% tab title="C#" %}

```
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
};
```

{% endtab %}
{% endtabs %}

**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.**

{% tabs %}
{% tab title="Java" %}

<pre class="language-java"><code class="lang-java"><strong>    ...
</strong><strong>    ObjectMapper objectMapper = new ObjectMapper();
</strong>    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();
}
    
</code></pre>

{% endtab %}

{% tab title="Python" %}

```python
serialized_body = json.dumps(body, separators=(',', ':'), ensure_ascii=False)
signature_contract = f"{platformId};{serialized_body};{secret}"
signature = hmac.new(secret.encode(), signature_contract.encode(), hashlib.sha256).hexdigest()
```

{% endtab %}

{% tab title="PHP" %}

```php
$signatureContract = $platformId .";". json_encode($body) .";". $secret;
$signature = hash_hmac('sha256', $signatureContract, $secret);
```

{% endtab %}

{% tab title="JS" %}

```
const serializedBody = JSON.stringify(body).replace(///g, "\/");
const signatureContract = `${platformId};${serializedBody};${secret}`;
const signature = crypto.createHmac("sha256", secret).update(signatureContract).digest("hex");
```

{% endtab %}

{% tab title="C#" %}

```
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();

```

{% endtab %}
{% endtabs %}

#### **Step 2 - Execution of the Request**

{% tabs %}
{% tab title="Java" %}

```java
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);
```

{% endtab %}

{% tab title="Python" %}

```python
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}')
```

{% endtab %}

{% tab title="PHP" %}

```php
$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);
```

{% endtab %}

{% tab title="JS" %}

```
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);
}
```

{% endtab %}

{% tab title="C#" %}

```
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}");
}

```

{% endtab %}
{% endtabs %}

**Signature use cases:**

1. When you call us, you should send the `x-signature` header, so we can validate the payload data integrity.
2. When you receive a response, you must validate the `x-signature` header presence and validate that it is valid.
3. When you receive a callback, you must validate the `x-signature` header presence and validate that it is valid.

**Postman create signature Pre-request Script:**

{% code fullWidth="false" %}

```
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);
}

```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://passimpay.gitbook.io/passimpay-api/example-of-a-signature.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
