# Authentication

The Solidgate API v1 uses a signature-based authentication model. Each request must carry two headers that are computed from your Public and Secret key pair.

**API keys**

To start accepting payments, even in the sandbox environment, you require credentials. These credentials are the Public `publicKey` and Secret `secretKey` keys. Apply these keys for direct API calls and to check the webhook signature.

- **Format:** Public keys use the prefix `api_pk_`, secret keys use the prefix `api_sk_`.
- **Source:** Get both keys from the Solidgate Hub by navigating to **Developers** > **Channel details**.
- **Webhook keys:** Separate pair with the prefixes `wh_pk_` / `wh_sk_`, used exclusively for validating webhook payloads.


Use the Public and Secret keys to calculate the signature, verifying both the source and the integrity of the request details transmitted between the merchant and gateway.

> Never expose your Secret key in client-side code or public repositories. Use it only in secure server-side environments.


**Required headers**

Every request must include two custom headers.

Header
Description
Example
merchant
Your Public key, used to identify the requesting merchant.
api_pk_7b197...ba108f842
signature
HMAC-SHA512 signature that verifies the request source and data integrity.
MjNiYFdSdjVj...hYmNiZDY
Solidgate uses a similar authentication method for webhooks, with merchant and signature parameters included in the headers.

If you receive an incorrect signature response, verify your API keys and signature, then contact support for further assistance.

**Fail response authentication**

```json
{
  "error": {
    "code": "1.01",
    "messages": [
      "Authentication failed"
    ]
  }
}
```

## Generate signature

The signature value is a Base64-encoded string of the hexadecimal representation of an HMAC-SHA512 hash, created using the Secret key.

**Signature data**

Concatenate the following string and use it as the HMAC input `publicKey` + `jsonString` + `publicKey`

> For **GET** requests that do not have a body, the signature data is `publicKey` + `publicKey`.


Field
Description
Test data
publicKey
Your Public key.
api_pk_8f8a8k8e8k8e8y8
jsonString
Request body as a JSON string.
{"amount": "100", "currency": "USD"}
secretKey
Your Secret key.
api_sk_8f8a8k8e8k8e8y8
**Steps**

Use the 
generateSignature
function, which takes the data and the Secret key as parameters.
Generate the HMAC-SHA512 hash using the Secret key and data.
Get the hexadecimal representation of the hash.
Encode the hexadecimal representation of the hash directly to Base64.
**Expected signature with the test data above**

```text
MjFkZGE3ZTZjODc0YjY5YTczOTlmOTBlYjk0MDY1NThiODJiZmE3ZTgxOGJjMWUxYjNkNTFjMDNjZmUzOGRlMTBhZGEzMmYxMGY3NTBlOTBlMGZkNDUwZTRiNmI5YTBiYTVmZWM5NzcxMjU3OWM0MGU5Mzg1NTljOTE1NTVlNzA=
```

**Code examples**

```php
class SignatureGenerator
{
        public static function generateSignature(string $publicKey, string $jsonString, string $secret_key): string
    {
        $text = $publicKey . $jsonString . $publicKey;
        $hashedBytes = hash_hmac('sha512', $text, $secret_key);
        return base64_encode($hashedBytes);
    }
    public static function main(array $args): void
    {
        $public_key = 'api_pk_8f8a8k8e8k8e8y8';
        $json_string = '{"amount": "100", "currency": "USD"}';
        $secret_key = 'api_sk_8f8a8k8e8k8e8y8';
        $signature = self::generateSignature($public_key, $json_string, $secret_key);
        echo $signature . "\n";
    }
}

SignatureGenerator::main([]);
```

```js
const crypto = require('crypto');

function generateSignature(publicKey, jsonString, secretKey) {
  const data = publicKey + jsonString + publicKey;
  const hmac = crypto.createHmac('sha512', secretKey);
  hmac.update(data);
  const hash = hmac.digest();
  const hexHash = hash.toString('hex');
  return Buffer.from(hexHash).toString('base64');
}

const publicKey = 'api_pk_8f8a8k8e8k8e8y8';
const jsonString = '{"amount": "100", "currency": "USD"}';
const secretKey = 'api_sk_8f8a8k8e8k8e8y8';

const signature = generateSignature(publicKey, jsonString, secretKey);
console.log(signature);
```

```python
# This code is intended for Python 3 or newer.
import hashlib
import hmac
import base64

def generateSignature(public_key, json_string, secret_key):
    data = public_key + json_string + public_key
    hmac_hash = hmac.new(secret_key.encode('utf-8'), data.encode('utf-8'), hashlib.sha512).digest()
    return base64.b64encode(hmac_hash.hex().encode('utf-8')).decode('utf-8')

public_key = "api_pk_8f8a8k8e8k8e8y8"
json_string = "{\"amount\": \"100\", \"currency\": \"USD\"}"
secret_key = "api_sk_8f8a8k8e8k8e8y8"

signature = generateSignature(public_key, json_string, secret_key)
print(signature)
```

```go
package main

import (
	"crypto/hmac"
	"crypto/sha512"
	"encoding/base64"
	"encoding/hex"
	"fmt"
)

func generateSignature(publicKey, jsonString, secretKey string) string {
	data := publicKey + jsonString + publicKey
	mac := hmac.New(sha512.New, []byte(secretKey))
	mac.Write([]byte(data))
	hexHash := hex.EncodeToString(mac.Sum(nil))
	return base64.StdEncoding.EncodeToString([]byte(hexHash))
}

func main() {
	publicKey := "api_pk_8f8a8k8e8k8e8y8"
	jsonString := `{"amount": "100", "currency": "USD"}`
	secretKey := "api_sk_8f8a8k8e8k8e8y8"

	signature := generateSignature(publicKey, jsonString, secretKey)
	fmt.Println(signature)
}
```

```java
//dependency - https://mvnrepository.com/artifact/com.google.guava/guava
import com.google.common.hash.Hashing;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class SignatureGenerator {

  public static String generateSignature(String publicKey, String jsonString, String secretKey) {
    String text = publicKey + jsonString + publicKey;
    byte[] hashedBytes = Hashing.hmacSha512(secretKey.getBytes())
        .hashString(text, StandardCharsets.UTF_8).toString().getBytes();
    return Base64.getEncoder().encodeToString(hashedBytes);
  }

  public static void main(String[] args) {
    String publicKey = "api_pk_8f8a8k8e8k8e8y8";
    String jsonString = "{\"amount\": \"100\", \"currency\": \"USD\"}";
    String secretKey = "api_sk_8f8a8k8e8k8e8y8";
    String signature = generateSignature(publicKey, jsonString, secretKey);
    System.out.println(signature);
  }

}
```

```csharp
using System;
using System.Security.Cryptography;
using System.Text;

public class SignatureGenerator {

    public static string GenerateSignature(string publicKey, string jsonString, string secretKey) {
        string data = publicKey + jsonString + publicKey;
        byte[] secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);
        using (var hmac = new HMACSHA512(secretKeyBytes)) {
            byte[] hashBytes = hmac.ComputeHash(dataBytes);
            string hexHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
            byte[] base64Bytes = Encoding.UTF8.GetBytes(hexHash);
            string base64Signature = Convert.ToBase64String(base64Bytes);
            return base64Signature;
        }
    }

    public static void Main(string[] args) {
        string publicKey = "api_pk_8f8a8k8e8k8e8y8";
        string jsonString = "{\"amount\": \"100\", \"currency\": \"USD\"}";
        string secretKey = "api_sk_8f8a8k8e8k8e8y8";
        string signature = SignatureGenerator.GenerateSignature(publicKey, jsonString, secretKey);
        Console.WriteLine(signature);
    }
}
```

```kotlin
package com.solidgate.examples

// https://mvnrepository.com/artifact/com.google.guava/guava
import com.google.common.hash.Hashing
import java.nio.charset.StandardCharsets
import java.util.Base64

class SignatureGenerator {
    companion object {
        fun generateSignature(publicKey: String, jsonString: String, secretKey: String): String {
            val text = publicKey + jsonString + publicKey
            val hashedBytes = Hashing.hmacSha512(secretKey.toByteArray())
                .hashString(text, StandardCharsets.UTF_8).toString().toByteArray()
            return Base64.getEncoder().encodeToString(hashedBytes)
        }
    }
}

fun main() {
    val publicKey = "api_pk_8f8a8k8e8k8e8y8"
    val jsonString = "{\"amount\": \"100\", \"currency\": \"USD\"}"
    val secretKey = "api_sk_8f8a8k8e8k8e8y8"
    val signature = SignatureGenerator.generateSignature(publicKey, jsonString, secretKey)
    println(signature)
}
```

```ruby
require 'openssl'
require 'base64'

def generate_signature(public_key, json_string, secret_key)
  digest = OpenSSL::Digest.new('sha512')
  instance = OpenSSL::HMAC.new(secret_key, digest)
  instance.update(public_key + json_string + public_key)
  Base64.strict_encode64(instance.hexdigest)
end

# Example usage
public_key = "api_pk_8f8a8k8e8k8e8y8"
json_string = '{"amount": "100", "currency": "USD"}'
secret_key = "api_sk_8f8a8k8e8k8e8y8"

signature = generate_signature(public_key, json_string, secret_key)
puts "Signature value: #{signature}"
```

For help, contact us.