Integrating Cryptocurrency as a Payment Option with API

omolade11

Omolade Ekpeni

Posted on October 16, 2021

Integrating Cryptocurrency as a Payment Option with API

Continuous evolvement of cryptocurrency as a means of payment drives the need for multicurrency payment options on payment gateways. In this article, @tkings and I will be sharing a great solution that works for implementing cryptocurrency payment with API. 

An example of how you can implement cryptocurrency in your project using CoinForBarter is below:

Sending an API post request to https://api.coinforbarter.com/v1/payments with the required payload will generate a payment object that you can work with.

Example in javascript using axios is shown below

/**
*
 * @returns a CoinForBarter payment object
 */
const createPaymentObject = async () => {
  try {
    const url = "https://api.coinforbarter.com/v1/payments";
    const requestPayload = {
      txRef: "RX1",
      amount: 10,
      currency: "BTC",
      currencies: [],
      meta: {
        consumer_id: 23,
      },
      customer: "example@gmail.com",
      customerPhoneNumber: "+234xxxxxx",
      customerFullName: "John Doe",
    };
    const secretKey = "xxxxxxxxxxxxxxxxxxx";
    const headers = {
      Authorization: `Bearer ${secretKey}`,
    };
    const { data } = await axios.post(url, requestPayload, { headers });
    return data;
  } catch (error) {
    // console.log(error)
  }
};
Enter fullscreen mode Exit fullscreen mode

You will receive a response like below

{
    "status": "success",
    "data": {
        "payment": {
            "id": "613a1067500d0f0020adf882",
            "_id": "613a1067500d0f0020adf882",
            "status": "in progress",
            "description": "Payment from Dayne_OKon@gmail.com",
            "txRef": "hrgyuur743784",
            "redirectUrl": "",
            "amount": 0,
            "nairaValue": 0,
            "dollarValue": 0,
            "baseAmount": 0.01,
            "baseCurrency": "BTC",
            "currencies": [
                "BTC",
                "DOGE",
                "ETH",
                "USDT",
                "USDC",
                "BUSD",
                "DAI",
                "PAX",
                "BCH",
                "WBTC"
            ],
            "expiresBy": 0,
            "transactionFees": 0,
            "totalDue": 0,
            "customer": "Dayne_OKon@gmail.com",
            "customerDetails": {
                "email": "Dayne_OKon@gmail.com",
                "fullName": ""
            },
            "addressSentFrom": [],
            "transactionTimeLog": [
                {
                    "time": "2021–09–09T13: 47: 19.098Z",
                    "type": "event",
                    "event": "Started transaction"
                }
            ],
            "isCurrencyLocked": false,
            "createdAt": "2021–09–09T13: 47: 19.100Z"
        },
        "url": "https: //coinforbarter-checkout.herokuapp.com/v1/api-pay/6109aa97-ad5bab00–1b913f89–613a1067–500d0f00–20adf882"
    },
    "message": "payment created"
}
Enter fullscreen mode Exit fullscreen mode

There are two modes in which this payment object can be used to process a full payment,
• CoinForBarter hosted.
• Self hosted.

CoinForBarter Hosted

You can simply redirect your customer to the data.url field to complete the payment. This is referred to as the CoinForBarter Standard. You can read more from the CoinForBarter Standard Documentation.

It will open a payment gateway like below for the customer to complete the payment.

You can provide a redirectUrl to the request payload to redirect the customer to that url when the payment ends.
You can also provide a webhook as seen here.

Self Hosted

For the self hosted, you can have your own interface shown to the customer all through the payment process.

The payment process has the following cycle.

  • Select currency and network
  • Lock currency
  • Get address and amount the customer is to pay with from selected currency.

An example is shown below using Javascript axios

/**
 *
 * @param {string} paymentId the payment id gotten from data.id
 * @param {string} currency the selected currency to process the payment in eg BTC
 * @param {string} network the selected blockchain network of the currency eg. BEP20
 * @returns an updated payment object containing extra information based on selected currency and network
 */
const setCurrency = async (paymentId, currency, network) => {
  try {
    const url = `https://api.coinforbarter.com/v1/payments/${paymentId}/currency/set/${currency}/${network}`;
    const secretKey = "xxxxxxxxxxxxxxxxxxx";
    const headers = {
      Authorization: `Bearer ${secretKey}`,
    };
    const { data } = await axios.patch(url, {}, { headers });
    return data;
  } catch (error) {
    // console.log(error)
  }
};
Enter fullscreen mode Exit fullscreen mode

A list of supported currencies and their networks to choose from can be found here.

After selecting a currency, the returned payload will look like below

{
    "status": "success",
    "data": {
        "id": "60d461fe6410f43ce05be378",
        "status": "in progress",
        "description": "Payment from Jody_Wolff21@hotmail.com",
        "txRef": "hrgyuur743784",
        "fee": 0.00030047,
        "currency": "BTC",
        "currencyNetwork": "bitcoin",
        "amount": 0.01030047,
        "baseAmount": 0.01,
        "baseCurrency": "BTC",
        "currencies": [],
        "transactionFees": 0,
        "totalDue": 0,
        "customer": "Jody_Wolff21@hotmail.com",
        "customerDetails": {
            "email": "Jody_Wolff21@hotmail.com"
        },
        "addressInformation": {
            "address": "19xqUGJ5Keo1LjDfatShxfHcKQT6HV24x3",
            "network": "bitcoin",
            "id": "60c7ca61ef2a380a447ed864"
        },
        "addressSentFrom": [],
        "transactionTimeLog": [
            {
                "time": "2021–06–24T10:44:14.787Z",
                "type": "event",
                "event": "Started transaction"
            },
            {
                "time": "2021–06–24T10:44:54.905Z",
                "type": "event",
                "event": "set currency to BTC, bitcoin"
            },
            {
                "time": "2021–06–24T10:45:40.482Z",
                "type": "event",
                "event": "locked currency"
            }
        ],
        "isCurrencyLocked": true,
        "createdAt": "2021–06–24T10:44:14.788Z"
    },
    "message": "currency locked"
}
Enter fullscreen mode Exit fullscreen mode

The object above contains data.currency and data.currencyNetwork. This confirms that a currency has been selected. 
 data.amount is the amount to be paid now in the selected currency.

The next step will be to confirm that the transaction is to be made in our selected currency.

An example is below

/**
 *
 * @param {string} paymentId paymentId the payment id gotten from data.id
 * @returns an updated payment object containing extra information based on the locked currency and network
 */
const lockCurrency = async (paymentId) => {
  try {
    const url = `https://api.coinforbarter.com/v1/payments/${paymentId}/currency/lock`;
    const secretKey = "xxxxxxxxxxxxxxxxxxx";
    const headers = {
      Authorization: `Bearer ${secretKey}`,
    };
    const { data } = await axios.patch(url, {}, { headers });
    return data;
  } catch (error) {
    // console.log(error)
  }
};
Enter fullscreen mode Exit fullscreen mode

The data returned above is similar to this

 {
    "status": "success",
    "data": {
        "id": "60d461fe6410f43ce05be378",
        "status": "in progress",
        "description": "Payment from Jody_Wolff21@hotmail.com",
        "txRef": "hrgyuur743784",
        "fee": 0.00030047,
        "currency": "BTC",
        "currencyNetwork": "bitcoin",
        "amount": 0.01030047,
        "baseAmount": 0.01,
        "baseCurrency": "BTC",
        "currencies": [],
        "transactionFees": 0,
        "totalDue": 0,
        "customer": "Jody_Wolff21@hotmail.com",
        "customerDetails": {
            "email": "Jody_Wolff21@hotmail.com"
        },
        "addressInformation": {
            "address": "19xqUGJ5Keo1LjDfatShxfHcKQT6HV24x3",
            "network": "bitcoin",
            "id": "60c7ca61ef2a380a447ed864"
        },
        "addressSentFrom": [],
        "transactionTimeLog": [
            {
                "time": "2021–06–24T10: 44: 14.787Z",
                "type": "event",
                "event": "Started transaction"
            },
            {
                "time": "2021–06–24T10: 44: 54.905Z",
                "type": "event",
                "event": "set currency to BTC, bitcoin"
            },
            {
                "time": "2021–06–24T10: 45: 40.482Z",
                "type": "event",
                "event": "locked currency"
            }
        ],
        "isCurrencyLocked": false,
        "createdAt": "2021–06–24T10: 44: 14.788Z"
    },
    "message": "currency locked"
}
Enter fullscreen mode Exit fullscreen mode

The object above contains data.isCurrencyLocked This confirms that the transaction has been locked for the selected currency. 
 data.addressInformation shows the address and network the amount is to be sent to.

The final step is to get notified and verify when a payment has been received.

You can use the CoinForBarter Webhooks to get notified.

Then verify the transaction by checking the data.amountReceived to be equal to data.amount with the following endpoint.

/**
 *
 * @param {string} paymentId paymentId paymentId the payment id gotten from data.id
 * @returns the present state of the payment object
 */
const verifyPayment = async (paymentId) => {
  try {
    const url = `https://api.coinforbarter.com/v1/payments/${paymentId}`;
    const secretKey = "xxxxxxxxxxxxxxxxxxx";
    const headers = {
      Authorization: `Bearer ${secretKey}`,
    };
    const { data } = await axios.patch(url, {}, { headers });
    return data;
  } catch (error) {
    // console.log(error)
  }
};
Enter fullscreen mode Exit fullscreen mode

You can get your secret key on your CoinForBarter's dashboard.

You can also use the data.status to be success if payment was successful, error if payment failed, inProgress if payment is in progress or cancelled if payment was cancelled.

In this article, we learnt how to integrate cryptocurrency as a payment option with APIs. @tkings and I wrote it. We previously wrote about how to implement cryptocurrency as a means of payment using html and javascript. In the future, we will be writing on implementing it using React and React Native. We will appreciate your comments, and if you have any questions, do not hesitate to hit either Kingsley or me up on Twitter.

💖 💪 🙅 🚩
omolade11
Omolade Ekpeni

Posted on October 16, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related