JWT Token Generation

For Token Generation remember that you must first :

  1. Request API access by emailing to [email protected]

Once you have received you KeyID and Secrets, you can generate JWT Tokens as follows

Golang

package main

import (
	"errors"
	"sync"
	"time"

	"log"

	"github.com/golang-jwt/jwt"
)

var (
	jwtMutex sync.Mutex
)

func main() {
	password := "SecretPasswordGivenByR2"
	kid := "keyIdGivenByR2"
  // MerchantId is optional, if you don't want to filter by merchant, send an empty string as ""
  // But is required for embedabble components
  mid := "MerchantId"
  // Optional if you only operate on one country
  // Otherwise include the ISO_2 country code
  country := "MX"

	jwtToken, err := GenerateJWT(kid, password, mid, country)
	if err != nil {
		log.Println("Error generating jwt ", err.Error())
	}
	log.Println("Jwt generated ", jwtToken)
}

func GenerateJWT(kid, mySecretKey, merchantId, country string) (jwtToken string, err error) {
	// if you are not into a http handler or goroutine, you should add a unique access to this function.
	jwtMutex.Lock()
	defer jwtMutex.Unlock()
	// End of unique access
	
	if kid == "" || mySecretKey == "" {
		return "", errors.New("error, missing kid and secret")
	}
	token := jwt.New(jwt.SigningMethodHS256)
	token.Header["kid"] = kid

	claims := token.Claims.(jwt.MapClaims)

  // This is an example, you should set your own expiration in seconds
	tokenExpiration := 60

	if merchantId != "" {
		claims["mid"] = merchantId // Optional
	}
  if country != "" {
		claims["country"] = country // Optional
	}
	claims["exp"] = time.Now().Add(time.Second * time.Duration(tokenExpiration)).Unix()

	tokenString, err := token.SignedString([]byte(mySecretKey))

	if err != nil {
		log.Println("Something Went Wrong: ", err.Error())
		return "", err
	}

	return tokenString, nil
}

Python

import datetime, threading

# You should install this library. pip3 install pyjwt
import jwt

# If you need to be sure, that this function class is used by one thread at a time.
mutex=threading.Lock()
# Create a class
class Jwt:
    def __init__(my_jwt, secret, kid):
        my_jwt.secret = secret
        my_jwt.kid = kid

# Adding a function to generate JWT
    def generetaJWT(instance, mid, country):
        # If you need to be sure that this function class is used by one thread at a time.
        global mutex
        # This is an example, you should set your own expiration in seconds
        expiration=60
        payload = {"exp": datetime.datetime.now(
            tz=datetime.timezone.utc) + datetime.timedelta(seconds=expiration)}
        mid = ""
        if mid != "":
            payload.mid = mid
        country = ""
        if country != "":
            payload.cuntry = country
        encoded_jwt = jwt.encode(
            payload, secret, algorithm="HS256", headers={"kid": kid})
        # If you need to be sure that this function class is used by one thread at a time.
        mutex.release()
        return encoded_jwt


# Main implementation
secret = "SecretPasswordGivenByR2"
kid = "keyIdGivenByR2"
# MerchantId is optional, if you don't want to filter by merchant, send an empty string as ""
# Required for embeddable components
merchantId = "MerchantId"
# Optional, but required if you operate on multiple countries
country = "CL"
# If you need to be sure that this function class is used by one thread at a time.
mutex.acquire()
jwtInstance = Jwt(secret, kid)
print(jwtInstance.generetaJWT(merchantId, country))