:zap:Java
package com.clara.integrations.claraapi.example;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import javax.net.ssl.*;
import java.io.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws Exception {
Certificate publicCert = loadFromFile(new File("path-to-your-certificate.crt"));
PrivateKey privateKey = readPKCS8PrivateKey(new File("path-to-your-certificate.crt.key"));
KeyStore ks = loadKeyStore(publicCert, privateKey);
TrustManager[] trustManagers = getTrustManagers();
KeyManager[] keyManagers = getKeyManagers(ks);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
String clientId = "YOUR-CLIENT-ID";
String clientSecret = "YOUR-CLIENT-SECRET";
String auth = clientId + ":" + clientSecret;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
HttpRequest request = HttpRequest.newBuilder(new URI("https://public-api.mx.clara.com/oauth/token")).header("Authorization", "Basic " + encodedAuth).POST(HttpRequest.BodyPublishers.ofByteArray("".getBytes())).build();//use mx, co, br depending on your country you are based
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode() + " Body: " + response.body());
// Extract token from response, then call a real endpoint
// Assuming token is parsed from response.body() into accessToken variable
String accessToken = "YOUR-ACCESS-TOKEN"; // replace with parsed token
HttpRequest txRequest = HttpRequest.newBuilder(new URI("https://public-api.mx.clara.com/api/v3/transactions"))
.header("Authorization", "Bearer " + accessToken)
.GET()
.build();
HttpResponse<String> txResponse = client.send(txRequest, HttpResponse.BodyHandlers.ofString());
System.out.println("Transactions Status: " + txResponse.statusCode() + " Body: " + txResponse.body());
}
private static Certificate loadFromFile(File file) throws CertificateException, FileNotFoundException {
CertificateFactory fact = CertificateFactory.getInstance("X.509");
return fact.generateCertificate(new FileInputStream(file.getPath()));
}
private static TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
return trustManagerFactory.getTrustManagers();
}
private static KeyManager[] getKeyManagers(KeyStore identityStore) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(identityStore, "".toCharArray());
return keyManagerFactory.getKeyManagers();
}
private static KeyStore loadKeyStore(Certificate cert, PrivateKey privateKey) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
KeyStore store;
store = KeyStore.getInstance("pkcs12");
store.load(null, "".toCharArray());
store.setKeyEntry("client", privateKey, "".toCharArray(), new Certificate[] { cert });
return store;
}
private static PrivateKey readPKCS8PrivateKey(File file) throws Exception {
Security.addProvider(new BouncyCastleProvider());
try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(content);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(spec);
}
}
}
:zap:C# - Windows
Note: The Windows platform does not support CRT or PEM files directly in .NET, so you need to convert them into a PFX file. You can do this by running the following command in your terminal using the OpenSSL tool, while generating the file you will be asked to create a password, you can choose a password in this step to be used in your code after.openssl pkcs12 -export -out certificate.pfx -inkey certificate.key -in certificate.crt
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Example
{
class Program
{
static async Task Main(string[] args)
{
X509Certificate2 certificate = new X509Certificate2("prod-mx.pfx", "your-password"); //BE SURE THE FILE IS THE FOLDER
var clientHandler = new HttpClientHandler();
clientHandler.ClientCertificates.Add(certificate);
clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
clientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
var client = new HttpClient(clientHandler);
var clientId = ""; //CHANGE THIS FOR YOUR CREDENTIALS
var clientSecret = ""; //CHANGE THIS FOR YOUR CREDENTIALS
var base64Credentials = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));;
var request = new HttpRequestMessage(HttpMethod.Post, "https://public-api.mx.clara.com/oauth/token"); //WATCH YOUR COUNTRY
request.Headers.Add("Authorization", "Basic " + base64Credentials);
request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(""));
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status: {response.StatusCode}, Body: {responseBody}");
// Use the token to call a real endpoint
// Parse access_token from responseBody JSON, then:
var accessToken = "YOUR-ACCESS-TOKEN"; // replace with parsed token
var txRequest = new HttpRequestMessage(HttpMethod.Get, "https://public-api.mx.clara.com/api/v3/transactions");
txRequest.Headers.Add("Authorization", "Bearer " + accessToken);
var txResponse = await client.SendAsync(txRequest);
var txBody = await txResponse.Content.ReadAsStringAsync();
Console.WriteLine($"Transactions Status: {txResponse.StatusCode}, Body: {txBody}");
}
}
}
:zap:C# - macOs or Linux
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Example
{
class Program
{
static async Task Main(string[] args)
{
X509Certificate2 certificate = new X509Certificate2("prod-mx.crt"); //BE SURE THE FILE IS THE FOLDER
using (StreamReader reader = new StreamReader("prod-mx.key")) //BE SURE THE FILE IS THE FOLDER
{
string privateKeyText = await reader.ReadToEndAsync();
RSA privateKey = RSA.Create();
privateKey.ImportFromPem(privateKeyText);
certificate = certificate.CopyWithPrivateKey(privateKey);
}
var clientHandler = new HttpClientHandler();
clientHandler.ClientCertificates.Add(certificate);
clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
clientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
var client = new HttpClient(clientHandler);
var clientId = ""; //CHANGE THIS FOR YOUR CREDENTIALS
var clientSecret = ""; //CHANGE THIS FOR YOUR CREDENTIALS
var base64Credentials = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));;
var request = new HttpRequestMessage(HttpMethod.Post, "https://public-api.mx.clara.com/oauth/token"); //WATCH YOUR COUNTRY
request.Headers.Add("Authorization", "Basic " + base64Credentials);
request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(""));
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status: {response.StatusCode}, Body: {responseBody}");
// Use the token to call a real endpoint
// Parse access_token from responseBody JSON, then:
var accessToken = "YOUR-ACCESS-TOKEN"; // replace with parsed token
var txRequest = new HttpRequestMessage(HttpMethod.Get, "https://public-api.mx.clara.com/api/v3/transactions");
txRequest.Headers.Add("Authorization", "Bearer " + accessToken);
var txResponse = await client.SendAsync(txRequest);
var txBody = await txResponse.Content.ReadAsStringAsync();
Console.WriteLine($"Transactions Status: {txResponse.StatusCode}, Body: {txBody}");
}
}
}
:zap:Python 3
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.ssl_ import create_urllib3_context
import base64
class SSLAdapter(HTTPAdapter):
def __init__(self, certfile, keyfile, cafile):
self.context = create_urllib3_context()
self.context.load_cert_chain(certfile, keyfile)
self.context.load_verify_locations(cafile)
super().__init__()
def init_poolmanager(self, *args, **kwargs):
kwargs['ssl_context'] = self.context
return super().init_poolmanager(*args, **kwargs)
client_id = 'YOUR-CLIENT-ID'
client_secret = 'YOUR-CLIENT-SECRET'
auth = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
session = requests.Session()
session.mount("https://", SSLAdapter("path-to-your-certificate.crt", "path-to-your-certificate.crt.key", "path-to-ca-cert.pem"))
headers = {
"Authorization": f"Basic {auth}"
}
response = session.post("https://public-api.mx.clara.com/oauth/token", headers=headers)
print(f"Status: {response.status_code} Body: {response.text}")
# Use the token to call a real endpoint
token_data = response.json()
access_token = token_data["access_token"]
tx_headers = {
"Authorization": f"Bearer {access_token}"
}
tx_response = session.get("https://public-api.mx.clara.com/api/v3/transactions", headers=tx_headers)
print(f"Transactions Status: {tx_response.status_code} Body: {tx_response.text}")
:zap:Go
Go Lang
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
cert, err := tls.LoadX509KeyPair("path-to-your-certificate.crt", "path-to-your-certificate.crt.key")
if err != nil {
log.Fatalf("failed to load client cert: %v", err)
}
caCert, err := ioutil.ReadFile("path-to-ca-cert.pem")
if err != nil {
log.Fatalf("failed to load CA cert: %v", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
}
clientID := "YOUR-CLIENT-ID"
clientSecret := "YOUR-CLIENT-SECRET"
auth := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + clientSecret))
req, err := http.NewRequest("POST", "https://public-api.mx.clara.com/oauth/token", nil)
if err != nil {
log.Fatal(err)
}
req.Header.Add("Authorization", "Basic "+auth)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Status: %s Body: %s\n", resp.Status, string(body))
// Use the token to call a real endpoint
// Parse access_token from body JSON, then:
accessToken := "YOUR-ACCESS-TOKEN" // replace with parsed token from body
txReq, err := http.NewRequest("GET", "https://public-api.mx.clara.com/api/v3/transactions", nil)
if err != nil {
log.Fatal(err)
}
txReq.Header.Add("Authorization", "Bearer "+accessToken)
txResp, err := client.Do(txReq)
if err != nil {
log.Fatal(err)
}
defer txResp.Body.Close()
txBody, _ := ioutil.ReadAll(txResp.Body)
fmt.Printf("Transactions Status: %s Body: %s\n", txResp.Status, string(txBody))
}
:zap:JavaScript/Node.Js
const https = require('https');
const fs = require('fs');
const path = require('path');
const clientId = 'YOUR-CLIENT-ID';
const clientSecret = 'YOUR-CLIENT-SECRET';
const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
const options = {
hostname: 'public-api.mx.clara.com',
port: 443,
path: '/oauth/token',
method: 'POST',
key: fs.readFileSync('path-to-your-certificate.crt.key'),
cert: fs.readFileSync('path-to-your-certificate.crt'),
ca: fs.readFileSync('path-to-ca-cert.pem'),
headers: {
'Authorization': `Basic ${auth}`
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
console.log(`Status: ${res.statusCode} Body: ${data}`);
// Use the token to call a real endpoint
const tokenData = JSON.parse(data);
const accessToken = tokenData.access_token;
const txOptions = {
hostname: 'public-api.mx.clara.com',
port: 443,
path: '/api/v3/transactions',
method: 'GET',
key: fs.readFileSync('path-to-your-certificate.crt.key'),
cert: fs.readFileSync('path-to-your-certificate.crt'),
ca: fs.readFileSync('path-to-ca-cert.pem'),
headers: {
'Authorization': `Bearer ${accessToken}`
}
};
const txReq = https.request(txOptions, (txRes) => {
let txData = '';
txRes.on('data', (chunk) => { txData += chunk; });
txRes.on('end', () => {
console.log(`Transactions Status: ${txRes.statusCode} Body: ${txData}`);
});
});
txReq.on('error', (e) => { console.error(e); });
txReq.end();
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
