# API Authentication

The 2Checkout API requires you to authenticate for any requests. Follow the steps below to learn how to authenticate in order to use the 2Checkout API.

## How to authenticate

This is achieved via digest access authentication, using your **Merchant Code** & **Secret Key**. These can be found in your 2Checkout [Merchant Control Panel](https://secure.2checkout.com/cpanel), under **Integrations** *>* [Webhooks & API](https://secure.2checkout.com/cpanel/webhooks_api.php).

<div data-with-frame="true"><figure><img src="/files/WtywmHuxwBNnm6EwZ8Uk" alt=""><figcaption></figcaption></figure></div>

To authenticate, you must first generate a hash code that will then be used together with your Merchant Code. The string used in the hash function is generated by concatenating the following values (in this order):

1. Length of your Merchant Code
2. Merchant Code
3. Length of the current DateTime formatted as Y-m-d H:i:s
4. Current DateTime&#x20;

{% hint style="info" %}
For example, for Merchant Code “YOURCODE123“ trying to authenticate on 2020-06-18 08:05:46 GMT, the string that needs to be hashed would look like: “11YOURCODE123192020-06-18 08:05:46”.
{% endhint %}

Once the string has been generated, it needs to be hashed using the **SHA algorithm** and the Secret Key available in the 2Checkout Merchant Control Panel.&#x20;

## Hashing algorithms available

Starting with API 6.0, authentication in the API supports the 256-bit variant of each of the two SHA (Secure Hash Algorithm) families, meaning SHA2 and SHA3.

In PHP, this would look like:

```php
$merchantCode = "YOUR_MERCHANT_CODE";  
$key = "YOUR_SECRET_KEY";  

$string = strlen($merchantCode) . $merchantCode . strlen(gmdate('Y-m-d H:i:s')) . gmdate('Y-m-d H:i:s');  

$algo = "SHA3-256"; 

$hash = hash_hmac($algo, $string, $key);
```

## Authenticating on REST protocol

Authentication on REST is done via an X-Avangate-Authentication header provided on all requests. The X-Avangate-Authentication header value contains the Merchant Code, request DateTime, and the hash generated above.&#x20;

The format of the header is:

```apache
X-Avangate-Authentication: code="{MERCHANT_CODE}" date="{REQUEST_DATE_TIME}" hash="{HASH}" algo="{ALGO}"
```

Once the hash has been generated, this can be used to authenticate on any of the three protocols.

```php
<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 

# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm , $string, $key); 
$payload = ''; 

$ch = curl_init(); 

$headerArray = [ 
"Content-Type: application/json", 
"Accept: application/json", 
"X-Avangate-Authentication: code=\"{$merchantCode}\" date=\"{$date}\" hash=\"{$hash}\" algo=\"{$hashAlgorithm}\"" 
];
 
curl_setopt($ch, CURLOPT_URL, $host); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_POST, FALSE); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSLVERSION, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); 

$response = curl_exec($ch);
```

## Authenticating on SOAP protocol

Authentication on SOAP is done via the login method, using the hash generated above. Once the session id is returned by the login method, this will be used in all subsequent API requests. &#x20;

A full-working example in PHP for SOAP login looks like:

```php
<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 

# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm, $string, $key); 

try { 
    $sessionID = $client->login($merchantCode, $date, $hash, $hashAlgorithm); 
    print_r($sessionID); 
} catch (SoapFault $e) { 
    echo $e->getMessage(); 
}
```

## Authenticating on RPC protocol

Authentication on RPC is done via the login method, using the hash generated above. Once the session id is returned by the login method, this will be used in all subsequent API requests.

A full-working example in PHP for RPC login looks like:

```php
<?php 
$merchantCode = "YOUR_MERCHANT_CODE"; 
$key = "YOUR_SECRET_KEY"; 
$date = gmdate('Y-m-d H:i:s'); 
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 
 
# sha256 or sha3-256 
$hashAlgorithm = 'sha256'; 
$hash = hash_hmac($hashAlgorithm , $string, $key); 

$i = 1; 
$jsonRpcRequest = new stdClass(); 
$jsonRpcRequest->jsonrpc = '6.0'; 
$jsonRpcRequest->method = 'login'; 
$jsonRpcRequest->params =[$merchantCode, $date, $hash, $hashAlgorithm]; 
$jsonRpcRequest->id = $i++; 
$sessionID = callRPC($jsonRpcRequest, $host);
```

## SHA algorithm

Generating the hash needed to authenticate using SHA-2 or SHA-3 is similar to using MD5, with the note that in the list of parameters, the hashing algorithm must be specified (the last parameter in the list).&#x20;

### REST example

```php
<?php
$merchantCode = "YOURCODE123";
$key = "SECRET_KEY";

$apiVersion = '6.0';
$resource = 'leads';
$host = "https://api.2checkout.com/rest/".$apiVersion."/".$resource."/"; 

$date = gmdate('Y-m-d H:i:s');
$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date;
$hash = hash_hmac($algo , $string, $key); 
$payload = ''; 

$ch = curl_init();

$headerArray = array( 
    "Content-Type: application/json", 
    "Accept: application/json", 
    "X-Avangate-Authentication: code=\"{$merchantCode}\" date=\"{$date}\" hash=\"{$hash}\" algo=\"{$algo}\"" 
);

curl_setopt($ch, CURLOPT_URL, $host); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, FALSE); 
curl_setopt($ch, CURLOPT_POST, FALSE); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSLVERSION, 0); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); 
 
$response = curl_exec($ch); 
```

### SOAP example

```php
<?php
$host  = "https://api.2checkout.com";
$soapClient = new SoapClient($host . "/soap/6.0/?wsdl", array(
    'location' => $host . "/soap/6.0/",
    "stream_context" => stream_context_create(array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false
        )
    ))
));

$merchantCode = "YOURCODE123";
$key = "SECRET_KEY";
$now = gmdate('Y-m-d H:i:s');

$string = strlen($merchantCode) . $merchantCode . strlen($now) . $now;
$hash   = hash_hmac($algo, $string, $key);

try {
    $sessionID = $soapClient->login($merchantCode, $now, $hash);
}

catch (SoapFault $e) {
    echo "Authentication: " . $e->getMessage();
    exit;
}
```

### JSON-RPC example

```php
<?php 
$host = 'https://api.2checkout.com/rpc/6.0/'; 

function callRPC($Request, $host, $Debug = true) { 
    $curl = curl_init($host); 
    curl_setopt($curl, CURLOPT_POST, 1); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($curl, CURLOPT_VERBOSE, true); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($curl, CURLOPT_SSLVERSION, 0); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json')); 
    $RequestString = json_encode($Request); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $RequestString); 
    if ($Debug) {
        $RequestString; 
    } 
    $ResponseString = curl_exec($curl); 
    if ($Debug) { 
        $ResponseString; 
    } 
    if (!empty($ResponseString)) { 
        var_dump($ResponseString); 
        $Response = json_decode($ResponseString); 
        if (isset($Response->result)) { 
            return $Response->result; 
        } 
        if (!is_null($Response->error)) { 
            var_dump($Request->method, $Response->error); 
        } 
    } else { 
        return null; 
    }
}

$merchantCode = "YOURCODE123";  
$key = "SECRET_KEY";  
$date = gmdate('Y-m-d H:i:s'); 

$string = strlen($merchantCode) . $merchantCode . strlen($date) . $date; 
$hash = hash_hmac($algo, $string, $key); 

$i = 1;

$jsonRpcRequest = new stdClass(); 
$jsonRpcRequest->jsonrpc = '2.0'; 
$jsonRpcRequest->method = 'login'; 
$jsonRpcRequest->params = array($merchantCode, $date, $hash, $algo); 
$jsonRpcRequest->id = $i++;


$sessionID = callRPC($jsonRpcRequest, $host);
```

## Integration test cases

Testing your integration should be straightforward:

* For SOAP and JSON-RPC, run a request on the login method and check if you are getting a successful result with an alphanumeric session id.
* For REST, run a GET call or search request against a simple resource like payouts or leads. While the result may be empty if you do not have any activity yet, the HTTP response should be 200 OK, letting you know that the authentication was successful.

## Testing your API with Postman

{% hint style="info" %}
You can test your API using Postman only with the SHA256 version of the algorithm, as Postman does not support SHA3.
{% endhint %}

<div data-with-frame="true"><img src="/files/b07273b6974a613af0b25ea1d4c0a7b5c6f9ca82" alt=""></div>

<div data-with-frame="true"><img src="/files/d7df06b4fd23c3112c827ca5ef7af1542b4d196b" alt=""></div>


---

# 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://docs.2checkout.com/get-started-with-the-2checkout-api/get-started-with-the-2checkout-api/authentication-and-use-cases/api-authentication.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.
