DEV Community

Cover image for Accepting Multiple Currencies with SeerBit: A Developer's Guide

Accepting Multiple Currencies with SeerBit: A Developer's Guide

In today's global marketplace, offering multi-currency support is essential for businesses aiming to reach a diverse customer base. Allowing customers to pay in their preferred currency not only enhances user experience but also boosts conversion rates.

SeerBit, a leading payment gateway, provides robust multi-currency capabilities, enabling businesses to seamlessly accept payments from various regions.

SeerBit's Multi-Currency Capabilities

Supported Currencies and Regions

SeerBit supports a wide range of currencies across multiple African countries, including Nigeria, Ghana, Kenya, Senegal, and more. This extensive coverage ensures that businesses can cater to customers in their local currencies, fostering trust and convenience.

Automatic Currency Conversion Features

With SeerBit's intelligent payment routing, transactions are processed through optimal routes, ensuring successful payments. While SeerBit handles multiple currencies, it's essential for developers to manage currency conversions on the client side to display prices accurately to users.

Integrating multi-currency support into your Node.js application using SeerBit enhances your business's global reach by allowing customers to transact in their preferred currencies. This guide provides a step-by-step approach to implementing this functionality, including real-time currency conversion and payment processing with SeerBit's Node.js SDK.

Prerequisites

Before you begin, ensure you have the following:

Step 1: Setting Up the Project

1. Initialize the Project: Create a new Node.js project and install necessary dependencies.

   mkdir seerbit-multicurrency
   cd seerbit-multicurrency
   npm init -y
   npm install axios seerbit-nodejs node-schedule dotenv
Enter fullscreen mode Exit fullscreen mode

2. Configure Environment Variables: Create a .env file to securely store your API keys.

   SEERBIT_PUBLIC_KEY=your_seerbit_public_key
   SEERBIT_SECRET_KEY=your_seerbit_secret_key
   SEERBIT_BEARER_TOKEN=your_seerbit_bearer_token
   EXCHANGE_RATE_API_KEY=your_exchange_rate_api_key
Enter fullscreen mode Exit fullscreen mode

Ensure you replace placeholder text with your actual keys.

Step 2: Fetching Real-Time Exchange Rates

To display prices in various currencies, fetch the latest exchange rates.

1. Create a Module for Currency Conversion:

   // currencyConverter.js
   require('dotenv').config();
const axios = require('axios');

const apiKey = process.env.EXCHANGE_RATE_API_KEY;
const baseURL = 'https://api.currencyfreaks.com/v2.0/rates/latest';

async function convertCurrency(amount, fromCurrency, toCurrency){
    try{
        const response = await axios.get(baseURL, {
        params: {
            apikey: apiKey,
            symbols: toCurrency,
            base: fromCurrency
        }
        });
        const rate = response.data.rates[toCurrency];
        const convertedAmount = amount * rate;
        return convertedAmount.toFixed(2);
    }catch(error){
       console.error('Error fetching exchange rates:', error);
       throw new Error('Currency conversion failed');
    }
}

module.exports = convertCurrency;
Enter fullscreen mode Exit fullscreen mode

This module fetches the exchange rate between specified currencies and calculates the converted amount.

2. Implement Regular Updates for Exchange Rates:

To keep exchange rates current, schedule regular updates.

   // exchangeRateUpdater.js
   const schedule = require('node-schedule');
const axios = require('axios');
require('dotenv').config();

const apiKey = process.env.EXCHANGE_RATE_API_KEY;
const baseUrl = 'https://api.currencyfreaks.com/v2.0/rates/latest';

async function updateExchangeRates(){
    try {
        const response = await axios.get(baseUrl, {
          params: {apikey: apiKey}
        });

        // Save response.data rates to your database or in-memory store
        console.log('Exchange rates updated:', response.data.rates);
    }catch(error){
    console.error('Error updating exchange rates:', error);
    }
}

// Schedule the job to run hourly
schedule.scheduleJob('0 * * * *', updateExchangeRates);
Enter fullscreen mode Exit fullscreen mode

This script fetches and logs the latest exchange rates every hour.

Step 3: Generating the Bearer Token

To integrate SeerBit's payment services into your Node.js application, you'll need to generate a bearer token for API authentication. Here's how you can obtain this token and incorporate it into your existing code.

SeerBit requires an encrypted key, derived from your secret and public keys, to authenticate API requests. Follow these steps to generate the bearer token:

1. Prepare Your Keys:

  • Public Key: Obtain this from your SeerBit merchant dashboard.

  • Secret Key: Also available on your merchant dashboard.

2. Concatenate and Encrypt Keys:

Format: Combine your secret and public keys into a single string, separated by a period (.):

SECRET_KEY.PUBLIC_KEY
Enter fullscreen mode Exit fullscreen mode

Encryption: Send this concatenated string to SeerBit's encryption endpoint to receive an encrypted key.

3. Request the Encrypted Key:

Endpoint: POST https://seerbitapi.com/api/v2/encrypt/keys
Headers: Set Content-Type to application/json.
Body: Include the concatenated key in the following JSON format:

{
  "key": "SECRET_KEY.PUBLIC_KEY"
}
Enter fullscreen mode Exit fullscreen mode

Important Considerations:

  • Security: Handle your secret and public keys with care. Avoid exposing them in client-side code or public repositories.

  • Token Validity: The encryptedKey (bearer token) may have a validity period. Ensure you handle token expiration appropriately in your application.

  • Error Handling: Implement comprehensive error handling to manage potential issues during the token generation and payment initialization processes.

For detailed information, refer to SeerBit's official documentation on authentication and the Node.js SDK:

By following these steps, you can securely generate a bearer token and integrate SeerBit's payment services into your Node.js application.

Step 4: Processing Payments with SeerBit

Integrate SeerBit's payment gateway to handle transactions in the desired currency.

1. Initialize SeerBit's SDK:

   // seerbitPayment.js
   const {Client, Config, StandardCheckout} = require('seerbit-nodejs');
require('dotenv').config();

const config = new Config({
    publicKey: process.env.SEERBIT_PUBLIC_KEY,
    secretKey: process.env.SEERBIT_SECRET_KEY,
    bearerToken: process.env.SEERBIT_BEARER_TOKEN
});

const client = new Client(config);
const standardCheckout = new StandardCheckout(client);

async function initializePayment(amount, currency, email){
    const payload = {
        amount,
        callbackUrl: 'https://www.yourapp.com/callback',
        country: 'NG',
        currency,
        email,
        paymentReference: Date.now().toString()
    };

    try{
        const response = await standardCheckout.Initialize(payload);
        console.log('Payment initialized successfully:', response);
        return response;
    }catch(error){
        console.error('Error initializing payment:', error);
        throw error;
    }
}

module.exports = initializePayment;   
Enter fullscreen mode Exit fullscreen mode

This module sets up the SeerBit client and defines a function to initialize payments.

2. Integrate Conversion and Payment Initialization:

Combine currency conversion and payment initialization to handle multi-currency transactions.

   // app.js
   const convertCurrency = require('./currencyConverter');
   const initializePayment = require('./seerbitPayment');

   async function processPayment(amount, fromCurrency, toCurrency, email) {
       try {
           const convertedAmount = await convertCurrency(amount, fromCurrency, toCurrency);
            await initializePayment(convertedAmount, toCurrency, email);
       } catch (error) {
           console.error('Error processing payment:', error);
       }
   }

   // Example usage
   processPayment(100, 'USD', 'NGN', 'customer@example.com');
Enter fullscreen mode Exit fullscreen mode

This script converts the amount from the source currency to the target currency and then initializes the payment with SeerBit.

Results

Checkout Payment Link Generated
Checkout Payment Link Generated

Payment Form
Checkout Form

Download the source code from github...

Conclusion

By following these steps, you can implement multi-currency support in your Node.js application using SeerBit. This integration ensures that customers can transact in their preferred currencies, enhancing user experience and expanding your market reach.

For more detailed information and advanced configurations, refer to the SeerBit API Documentation.

Thanks for reading...
Happy Coding!

Top comments (0)