Merchant tokens

A Merchant token is a low privileged token that you can set granular permissions on. Merchant tokens are suitable for using in your applications, e.g. to create payment requests on a web server. Even though they have less privileges than a User token, Merchant tokens should still be looked after and if lost or compromised they should be deleted and re-created. Merchant tokens do not expire.

Merchant token permissions

Your system may require the capability to perform specific tasks automatically, like managing payment requests or handling payouts (excluding authorization). To enable these operations, you can assign appropriate permissions to the merchant token. For comprehensive information on the range of permissions available for merchant tokens, please have a look at the Merchant Token Permissions section in our documentation.

Pre-requisites

You will need the following parameters in order to request the following API endpoints:

  1. Merchant ID: This is the ID of the merchant that was created for you when you registered on the NoFrixion portal. You can get this ID by logging into NoFrixion portal and navigating to profile. You will see the list of merchants with their IDs under "Merchants". If you are using OAuth integration with MoneyMoov to get access token then you can use the Merchants API to get a list of merchants assigned to you.
  2. Access token: This is the user access token used for authorisation. If you are using NoFrixion portal, then you can generate a temporary user token by navigating to Create API token and selecting "User" as token type. If you are using your own client and are using OAuth integration then use the generated access token through OAuth.

Creating merchant tokens

When a merchant token is created using the MoneyMoov API, the access token is returned in the API response body. Note, it is not saved in the NoFrixion database, so must be captured and securely stored on the client side.

To create a merchant token use the Tokens API ) as shown below:

using System.Net.Http.Json;

const string baseUrl = "https://api-sandbox.nofrixion.com/api/v1/tokens";

var accessToken = "<ACCESS_TOKEN>";

var client = new HttpClient();

client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");

// Updated to an anonymous object for JSON serialization
var data = new
{
    MerchantID = "<YOUR_MERCHANT_ID>",
    Description = "API created token",
    // A comma separated list of merchant token permissions. 
    // Defaults to "CreatePaymentRequest"
    // Refer https://docs.nofrixion.com/reference/merchant-token-permissions to know more.
    // Alternatively, refer https://github.com/nofrixion/moneymoov-dotnet/blob/master/src/NoFrixion.MoneyMoov/Enums/MerchantTokenPermissionsEnum.cs
    Permissions = "<MERCHANT_TOKEN_PERMISSIONS>" // Ex: "CreatePaymentRequest,DeletePaymentRequest"
};

try
{
    // Using JsonContent to serialize your data object to JSON
    var response = await client.PostAsJsonAsync(baseUrl, data);
    if (response.IsSuccessStatusCode)
    {
        var responseBody = await response.Content.ReadFromJsonAsync<MerchantToken>();
        if (responseBody != null)
        {
            // Response body JSON contains merchant token - SAVE THIS! (it isn't stored in the MoneyMoov system)
            Console.WriteLine(responseBody);
        }
    }
    else
    {
        // HTTP error codes will return a MoneyMoov API problem object
        Console.WriteLine(await response.Content.ReadFromJsonAsync<ApiProblem>());
    }
}
catch (Exception e)
{
    Console.WriteLine($"Error: {e.Message}");
}

// Type declarations for returned data
record MerchantToken(string id, string merchantId, string description, string permissions, string inserted,
            string lastUpdated, string token);

record ApiProblem(string type, string title, int status, string detail);
const axios = require('axios');

// Base URL for the API
const baseUrl = "https://api-sandbox.nofrixion.com/api/v1/tokens";

// JWT token for authorization
const accessToken = "<ACCESS_TOKEN>";

// Creating an instance of axios with default headers
const client = axios.create({
    baseURL: baseUrl,
    headers: {
        "Accept": "application/json",
        "Authorization": `Bearer ${jwtToken}`
    }
});

// Data object to be sent in the POST request
const data = {
    MerchantID: "<YOUR_MERCHANT_ID>",
    Description: "API created token",
    // A comma separated list of merchant token permissions.
    // Defaults to "CreatePaymentRequest"
    // Refer to the API documentation for more details on permissions.
    Permissions: "<MERCHANT_TOKEN_PERMISSIONS>"
};

// Async function to make the POST request
async function createToken() {
    try {
        // Making a POST request to the API
        const response = await client.post('', data);

        // Check if the response status code is in the range of 200-299
        if (response.status >= 200 && response.status < 300) {
            // If the response is successful, log the response data
            // Response body JSON contains merchant token - SAVE THIS! (it isn't stored in the MoneyMoov system)
            console.log(response.data);
        } else {
            // Log any other HTTP status code as an error
            // HTTP error codes will return a MoneyMoov API problem object
            console.log('Error:', response.status, response.statusText);
        }
    } catch (error) {
        // Catch and log any error during the HTTP request
        console.error('Error:', error.message);
    }
}

// Call the function to execute the POST request
createToken();
import requests

# Base URL for the API
base_url = "https://api-sandbox.nofrixion.com/api/v1/tokens"

# Access token for authorization
access_token = "<ACCESS_TOKEN>"

# Headers for the request, including the Authorization header
headers = {
    "Accept": "application/json",
    "Authorization": f"Bearer {access_token}"
}

# Data object to be sent in the POST request
data = {
    "MerchantID": "<YOUR_MERCHANT_ID>",
    "Description": "API created token",
    # A comma separated list of merchant token permissions.
    # Defaults to "CreatePaymentRequest"
    # Refer to the API documentation for more details on permissions.
    "Permissions": "<MERCHANT_TOKEN_PERMISSIONS>"
}

# Making a POST request to the API
response = requests.post(base_url, json=data, headers=headers)

# Check if the response status code is in the range of 200-299
if 200 <= response.status_code < 300:
    # If the response is successful, print the response data
    # Response body JSON contains merchant token - SAVE THIS! (it isn't stored in the MoneyMoov system)
    print(response.json())
else:
    # Print any other HTTP status code as an error
    # HTTP error codes will return a MoneyMoov API problem object
    print('Error:', response.status_code, response.text)

# Exception handling is not included as requests does not raise exceptions for HTTP errors
# You may handle exceptions for network-related errors if needed

Viewing tokens

A list of tokens previously issued to a merchant can be retrieved using the Merchants API/tokens endpoint. Note, the actual tokens are not returned here:

using System.Net.Http.Json;

string merchantID = "<YOUR_MERCHANT_ID>";

int pageNumber = 1;

int pageSize = 10;

string getMerchantTokensAPIUrl = $"https://api-sandbox.nofrixion.com/api/v1/merchants/{merchantID}/tokens?pageNumber={pageNumber}&pageSize={pageSize}";

var accessToken = "<ACCESS_TOKEN>";

var client = new HttpClient();

client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");

try
{
    var response = await client.GetAsync(getMerchantTokensAPIUrl);
    if (response.IsSuccessStatusCode)
    {
        var merchantTokens = await response.Content.ReadFromJsonAsync<PageResponse<MerchantToken>>();
        
        if (merchantTokens.content != null && merchantTokens.content.Count != 0)
        {
            foreach (var merchantToken in merchantTokens.content)
            {
                // Display merchant tokens token information
                Console.WriteLine(merchantToken);
            }
        }
        else
        {
            Console.WriteLine("No merchant tokens found.");
        }
    }
    else
    {
        // HTTP error codes will return a MoneyMoov API problem object
        Console.WriteLine(await response.Content.ReadFromJsonAsync<ApiProblem>());
    }
}
catch (Exception e)
{
    Console.WriteLine($"Error: {e.Message}");
}

// Type definitions for returned data
record PageResponse<T>(List<T> content, int pageNumber, int pageSize, int totalPages, long totalSize);

record MerchantToken(string id, string merchantId, string description, string permissions, string inserted,
    string lastUpdated);

record ApiProblem(string type, string title, int status, string detail);
const axios = require('axios');

// Assign your merchant ID and access token
const merchantID = "<YOUR_MERCHANT_ID>";
const accessToken = "<ACCESS_TOKEN>";

// Setting the page number and page size for the request
const pageNumber = 1;
const pageSize = 10;

// Constructing the API URL with query parameters
const getMerchantTokensAPIUrl = `https://api-sandbox.nofrixion.com/api/v1/merchants/${merchantID}/tokens?pageNumber=${pageNumber}&pageSize=${pageSize}`;

// Creating an instance of axios with default headers
const client = axios.create({
    headers: {
        "Accept": "application/json",
        "Authorization": `Bearer ${accessToken}`
    }
});

// Async function to make the GET request
async function getMerchantTokens() {
    try {
        // Making a GET request to the API
        const response = await client.get(getMerchantTokensAPIUrl);

        if (response.status >= 200 && response.status < 300) {
            // If the response is successful, process the merchant tokens
            const merchantTokens = response.data;

            if (merchantTokens.content && merchantTokens.content.length !== 0) {
                merchantTokens.content.forEach(merchantToken => {
                    // Display merchant tokens token information
                    console.log(merchantToken);
                });
            } else {
                console.log("No merchant tokens found.");
            }
        } else {
            // HTTP error codes will return a MoneyMoov API problem object
            console.log('Error:', response.status, response.statusText);
        }
    } catch (error) {
        // Catch and log any error during the HTTP request
        console.error('Error:', error.message);
    }
}

// Call the function to execute the GET request
getMerchantTokens();
import requests

# Assign your merchant ID and access token
merchant_id = "<YOUR_MERCHANT_ID>"
access_token = "<ACCESS_TOKEN>"

# Setting the page number and page size for the request
page_number = 1
page_size = 10

# Constructing the API URL with query parameters
get_merchant_tokens_api_url = f"https://api-sandbox.nofrixion.com/api/v1/merchants/{merchant_id}/tokens?pageNumber={page_number}&pageSize={page_size}"

# Headers for the request
headers = {
    "Accept": "application/json",
    "Authorization": f"Bearer {access_token}"
}

# Function to make the GET request
def get_merchant_tokens():
    try:
        # Making a GET request to the API
        response = requests.get(get_merchant_tokens_api_url, headers=headers)

        if 200 <= response.status_code < 300:
            # If the response is successful, process the merchant tokens
            merchant_tokens = response.json()

            if merchant_tokens.get('content') and len(merchant_tokens['content']) != 0:
                for merchant_token in merchant_tokens['content']:
                    # Display merchant tokens token information
                    print(merchant_token)
            else:
                print("No merchant tokens found.")
        else:
            # HTTP error codes will return a MoneyMoov API problem object
            print('Error:', response.status_code, response.text)
    except Exception as e:
        # Catch and log any error during the HTTP request
        print(f'Error: {e}')

# Execute the function to make the GET request
get_merchant_tokens()

Deleting tokens

The Tokens API can be used to delete a merchant token as shown below. Replace <TOKEN_ID_TO_DELETE> with the token ID that you want to delete. You can get the token ID using the Merchants API/tokens endpoint as shown above.

using System.Net.Http.Json;

const string tokensAPIUrl = "https://api-sandbox.nofrixion.com/api/v1/tokens";

var accessToken = "<ACCESS_TOKEN>";

var client = new HttpClient();

client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");

string tokenIDToDelete = "<TOKEN_ID_TO_DELETE>";

try
{
    var response = await client.DeleteAsync($"{tokensAPIUrl}/{tokenIDToDelete}");
    if (response.IsSuccessStatusCode)
    {   
        //HTTP status "OK" on success.
        Console.WriteLine(response.StatusCode);
    }
    else
    {
        // HTTP error codes will return a MoneyMoov API problem object
        Console.WriteLine(await response.Content.ReadFromJsonAsync<ApiProblem>());
    }
}
catch (Exception e)
{
    Console.WriteLine($"Error: {e.Message}");
}

// Type definitions for returned data
record ApiProblem(string type, string title, int status, string detail);
const axios = require('axios');

// API URL for tokens
const tokensAPIUrl = "https://api-sandbox.nofrixion.com/api/v1/tokens";

// Access token for authorization
const accessToken = "<ACCESS_TOKEN>";

// Token ID to delete
const tokenIDToDelete = "<TOKEN_ID_TO_DELETE>";

// Creating an instance of axios with default headers
const client = axios.create({
    headers: {
        "Accept": "application/json",
        "Authorization": `Bearer ${accessToken}`
    }
});

// Async function to make the DELETE request
async function deleteToken() {
    try {
        // Making a DELETE request to the API
        const response = await client.delete(`${tokensAPIUrl}/${tokenIDToDelete}`);

        if (response.status >= 200 && response.status < 300) {
            // HTTP status "OK" on success
            console.log(response.status);
        } else {
            // HTTP error codes will return a MoneyMoov API problem object
            console.log('Error:', response.status, response.statusText);
        }
    } catch (error) {
        // Catch and log any error during the HTTP request
        console.error('Error:', error.message);
    }
}

// Call the function to execute the DELETE request
deleteToken();

import requests

# API URL for tokens
tokens_api_url = "https://api-sandbox.nofrixion.com/api/v1/tokens"

# Access token for authorization
access_token = "<ACCESS_TOKEN>"

# Token ID to be deleted
token_id_to_delete = "<TOKEN_ID_TO_DELETE>"

# Headers for the request
headers = {
    "Accept": "application/json",
    "Authorization": f"Bearer {access_token}"
}

# Function to make the DELETE request
def delete_token():
    try:
        # Making a DELETE request to the API
        response = requests.delete(f"{tokens_api_url}/{token_id_to_delete}", headers=headers)

        if response.status_code == 200:
            # HTTP status "OK" on success.
            print(response.status_code)
        else:
            # HTTP error codes will return a MoneyMoov API problem object
            # Note: For detailed error messages, you may need to parse the response content if it's JSON
            print('Error:', response.status_code, response.text)
    except Exception as e:
        # Catch and log any error during the HTTP request
        print(f'Error: {e}')

# Execute the function to make the DELETE request
delete_token()