Authorization
To interact with the Ecart Pay API, you must generate an authorization token. This token is required to authenticate your requests and ensure secure communication with the platform.
WARNINGTo follow the steps below, it is essential to have the corresponding API Keys. For more information, please refer to the following: API Keys
Generating Your Token
You can create your token by sending a POST
request using your Public Key and Private Key. These keys can be found in your API Settings section within your account.
Token Validity
- The generated token is valid for 1 hour.
- To avoid encountering an Unauthorized error when making API requests, ensure you generate a new token after the expiration period.
- Tokens must be kept secure and should be deleted when no longer in use.
Example Request
Here is an example of how to make a POST
request to generate your token:
curl --location --request POST 'https://sandbox.ecartpay.com/api/authorizations/token' \
--header 'Authorization: ••••••' \
--header 'Cookie: lang=en'
package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://sandbox.ecartpay.com/api/authorizations/token"
method := "POST"
client := &http.Client {
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "••••••")
req.Header.Add("Cookie", "lang=en")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
POST /api/authorizations/token HTTP/1.1
Host: sandbox.ecartpay.com
Authorization: ••••••
Cookie: lang=en
// OkHttp
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
.url("https://sandbox.ecartpay.com/api/authorizations/token")
.method("POST", body)
.addHeader("Authorization", "••••••")
.addHeader("Cookie", "lang=en")
.build();
Response response = client.newCall(request).execute();
// -------------------------------------------------------------
// Unirest
Unirest.setTimeouts(0, 0);
HttpResponse<String> response = Unirest.post("https://sandbox.ecartpay.com/api/authorizations/token")
.header("Authorization", "••••••")
.header("Cookie", "lang=en")
.asString();
// Fetch
const myHeaders = new Headers();
myHeaders.append("Authorization", "••••••");
myHeaders.append("Cookie", "lang=en");
const requestOptions = {
method: "POST",
headers: myHeaders,
redirect: "follow"
};
fetch("https://sandbox.ecartpay.com/api/authorizations/token", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.error(error));
// -------------------------------------------------------------
// jQuery
var settings = {
"url": "https://sandbox.ecartpay.com/api/authorizations/token",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "••••••",
"Cookie": "lang=en"
},
};
$.ajax(settings).done(function (response) {
console.log(response);
});
// -------------------------------------------------------------
// XHR
// WARNING: For POST requests, body is set to null by browsers.
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://sandbox.ecartpay.com/api/authorizations/token");
xhr.setRequestHeader("Authorization", "••••••");
// WARNING: Cookies will be stripped away by the browser before sending the request.
xhr.setRequestHeader("Cookie", "lang=en");
xhr.send();
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, "https://sandbox.ecartpay.com/api/authorizations/token");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Authorization: ••••••");
headers = curl_slist_append(headers, "Cookie: lang=en");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
res = curl_easy_perform(curl);
curl_slist_free_all(headers);
}
curl_easy_cleanup(curl);
// Axios
const axios = require('axios');
let config = {
method: 'post',
maxBodyLength: Infinity,
url: 'https://sandbox.ecartpay.com/api/authorizations/token',
headers: {
'Authorization': '••••••',
'Cookie': 'lang=en'
}
};
axios.request(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
// -------------------------------------------------------------
// Native
var https = require('follow-redirects').https;
var fs = require('fs');
var options = {
'method': 'POST',
'hostname': 'sandbox.ecartpay.com',
'path': '/api/authorizations/token',
'headers': {
'Authorization': '••••••',
'Cookie': 'lang=en'
},
'maxRedirects': 20
};
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", function (error) {
console.error(error);
});
});
// -------------------------------------------------------------
// Request
var request = require('request');
var options = {
'method': 'POST',
'url': 'https://sandbox.ecartpay.com/api/authorizations/token',
'headers': {
'Authorization': '••••••',
'Cookie': 'lang=en'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
// -------------------------------------------------------------
// Unirest
var unirest = require('unirest');
var req = unirest('POST', 'https://sandbox.ecartpay.com/api/authorizations/token')
.headers({
'Authorization': '••••••',
'Cookie': 'lang=en'
})
.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});
#import <Foundation/Foundation.h>
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://sandbox.ecartpay.com/api/authorizations/token"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSDictionary *headers = @{
@"Authorization": @"••••••",
@"Cookie": @"lang=en"
};
[request setAllHTTPHeaderFields:headers];
[request setHTTPMethod:@"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
dispatch_semaphore_signal(sema);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"%@",responseDictionary);
dispatch_semaphore_signal(sema);
}
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
open Lwt
open Cohttp
open Cohttp_lwt_unix
let reqBody =
let uri = Uri.of_string "https://sandbox.ecartpay.com/api/authorizations/token" in
let headers = Header.init ()
|> fun h -> Header.add h "Authorization" "••••••"
|> fun h -> Header.add h "Cookie" "lang=en"
in
Client.call ~headers `POST uri >>= fun (_resp, body) ->
body |> Cohttp_lwt.Body.to_string >|= fun body -> body
let () =
let respBody = Lwt_main.run reqBody in
print_endline (respBody)
// cURL
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://sandbox.ecartpay.com/api/authorizations/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'Authorization: ••••••',
'Cookie: lang=en'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
// -------------------------------------------------------------
// Guzzle
<?php
$client = new Client();
$headers = [
'Authorization' => '••••••',
'Cookie' => 'lang=en'
];
$request = new Request('POST', 'https://sandbox.ecartpay.com/api/authorizations/token', $headers);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();
// -------------------------------------------------------------
// HTTP_Request2
<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://sandbox.ecartpay.com/api/authorizations/token');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
'follow_redirects' => TRUE
));
$request->setHeader(array(
'Authorization' => '••••••',
'Cookie' => 'lang=en'
));
try {
$response = $request->send();
if ($response->getStatus() == 200) {
echo $response->getBody();
}
else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
}
catch(HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
// -------------------------------------------------------------
// pecl_http
<?php
$client = new http\Client;
$request = new http\Client\Request;
$request->setRequestUrl('https://sandbox.ecartpay.com/api/authorizations/token');
$request->setRequestMethod('POST');
$request->setOptions(array());
$request->setHeaders(array(
'Authorization' => '••••••',
'Cookie' => 'lang=en'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "••••••")
$headers.Add("Cookie", "lang=en")
$response = Invoke-RestMethod 'https://sandbox.ecartpay.com/api/authorizations/token' -Method 'POST' -Headers $headers
$response | ConvertTo-Json
# http.client
import http.client
conn = http.client.HTTPSConnection("sandbox.ecartpay.com")
payload = ''
headers = {
'Authorization': '••••••',
'Cookie': 'lang=en'
}
conn.request("POST", "/api/authorizations/token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
# Requests
import requests
url = "https://sandbox.ecartpay.com/api/authorizations/token"
payload = {}
headers = {
'Authorization': '••••••',
'Cookie': 'lang=en'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
# httr
library(httr)
headers = c(
'Authorization' = '••••••',
'Cookie' = 'lang=en'
)
res <- VERB("POST", url = "https://sandbox.ecartpay.com/api/authorizations/token", add_headers(headers))
cat(content(res, 'text'))
# RCurl
library(RCurl)
headers = c(
"Authorization" = "••••••",
"Cookie" = "lang=en"
)
res <- postForm("https://sandbox.ecartpay.com/api/authorizations/token", .opts=list(httpheader = headers, followlocation = TRUE), style = "httppost")
cat(res)
require "uri"
require "net/http"
url = URI("https://sandbox.ecartpay.com/api/authorizations/token")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = "••••••"
request["Cookie"] = "lang=en"
response = https.request(request)
puts response.read_body
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::builder()
.build()?;
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("Authorization", "••••••".parse()?);
headers.insert("Cookie", "lang=en".parse()?);
let request = client.request(reqwest::Method::POST, "https://sandbox.ecartpay.com/api/authorizations/token")
.headers(headers);
let response = request.send().await?;
let body = response.text().await?;
println!("{}", body);
Ok(())
}
# Httpie
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::builder()
.build()?;
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("Authorization", "••••••".parse()?);
headers.insert("Cookie", "lang=en".parse()?);
let request = client.request(reqwest::Method::POST, "https://sandbox.ecartpay.com/api/authorizations/token")
.headers(headers);
let response = request.send().await?;
let body = response.text().await?;
println!("{}", body);
Ok(())
}
# wget
wget --no-check-certificate --quiet \
--method POST \
--timeout=0 \
--header 'Authorization: ••••••' \
--header 'Cookie: lang=en' \
'https://sandbox.ecartpay.com/api/authorizations/token'
var request = URLRequest(url: URL(string: "https://sandbox.ecartpay.com/api/authorizations/token")!,timeoutInterval: Double.infinity)
request.addValue("••••••", forHTTPHeaderField: "Authorization")
request.addValue("lang=en", forHTTPHeaderField: "Cookie")
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
return
}
print(String(data: data, encoding: .utf8)!)
}
task.resume()
Example Response
{
"token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxODA0ODNiZWFiOWQ5NDVhODZkYTNjMSIsInVzZXIiOiJ1bmRlZmluZWQiLCJpYXQiOjE2ODQyNTUzMDAsImV4cCI6MTY4NDI1ODkwMH0.l8aMEUA8E-BZy3o6aiu3mZ5n5g2lH4YOaLN43lfg7dbxf0_dP_CZWvwIYtbhGAhJw7qZYlOfpT6_DoFaWNB9sQ"
}
Response Parameters
token
: A string representing the authorization token, which is used for authenticating subsequent API requests.
Making API Requests
The token must be used as an Authorization Header Token.
Request Header Format
Key | Value |
---|---|
Authorization | <token> |
This ensures that your requests are properly authenticated and processed by the API.
Security Guidelines
- Keep your token secure: Treat the token as sensitive information. Store it securely and avoid sharing it.
- Regenerate tokens periodically: Tokens expire after 1 hour, so you must regenerate and update your token in your application to maintain seamless communication with the API.
- Delete unused tokens: When a token is no longer required, ensure it is deleted to minimize security risks.
By adhering to these guidelines, you can ensure secure and uninterrupted access to the Ecart Pay API.
Updated about 2 months ago