Payment

Usage

You can import the SDK classes and types from the payment entrypoint:

import { PaymentSDK } from "@first-iraqi-bank/sdk/payment"

The PaymentSDK class has a static method that gives you an instance of the SDK configured with your API credentials:

fib.js
import { PaymentSDK } from "@first-iraqi-bank/sdk/payment"

const clientId = process.env.FIB_CLIENT_ID
const clientSecret = process.env.FIB_CLIENT_SECRET
const environment = process.env.FIB_ENV // 'dev', 'stage', or 'prod'

export const FIB = PaymentSDK.getClient(clientId, clientSecret, environment)

Now you can import FIB from anywhere in your project and call its methods to create payments, check payment status or canceling them.

TIP

Checkout FIB Web Payment documentations for more info and how to obtain your credentials

  • authenticate(signal?: AbortSignal): Authenticates the client and returns an access token.
  • createPayment(paymentInput: PaymentInput, accessToken: string, signal?: AbortSignal): Creates a payment.
  • getPaymentStatus(paymentId: string, accessToken: string, signal?: AbortSignal): Gets the status of a payment.
  • cancelPayment(paymentId: string, accessToken: string, signal?: AbortSignal): Cancels a payment.
  • refundPayment(paymentId: string, accessToken: string, signal?: AbortSignal): Refunds a payment.

authenticate

This method sends a request to the First Iraqi Bank's identity server, giving you necessary token and other related information to authenticate your next requests like creating or canceling a payment.

import { FIB } from "./fib.js"

const res = await FIB.authenticate()
const { access_token, expires_in } = await res.json()

access_token is the most important part of the response, since you need to pass it to the next request otherwise it'll fail with Authentication error!

WARNING

Access tokens are designed to be short-lived, expires_in will tell you how many seconds you have until the access token expires. Make sure to fetch a new access token before your next API call if the token is expired by calling authenticateas described above.


createPayment

This method sends a request to the First Iraqi Bank's server, creating a payment based on the provided information, which are parameters to function:

  1. payment: an object with below possible properties:

    • amount: a number, indicating the payment's amount in IQD. Must be bigger than 250.

    • description (optional): a string used as description and might be shown to the customer when they try to pay in the FIB app.

    • expiresIn (optional): a Duration object indicating when the transaction expires, it must be:

      1. Bigger than 5 Minutes
      2. Smaller than 48 Hours
    • refundableFor (optional): a Duration object indicating till when the transaction can be refunded after it was paid, it must be:

      1. Bigger than 12 Hours
      2. Smaller than 7 Days
    • redirectUri (optional): an instance of URL class, you can provide a URL of your app where the user should be redirected when the payment was authorized, for example if you want FIB app to redirect user back to some screen inside your app/website, this is used when you use Pay with FIB button in your.

    • statusCallbackUrl (optional): an instance of URL class, this must be the URL of your backend and specifically of an endpoint that can accept POST request, as FIB backend will call this endpoint when the status of the transaction changes. Omit it if you're not interested.

  • extraData (optional): an array of up to 10 objects, each with a key and value property, allowing you to attach additional metadata to the payment (e.g., order IDs, customer info, etc.).
  1. accessToken: a previously fetched access token from authenticate method.
  2. signal (optional): an AbortSignal that can use to abort the fetch request. Checkout Canceling a request on MDN for detailed explanation.

Example:

import { FIB } from "./fib.js"

const paymentInput = {
  amount: 1000, // amount in IQD
  description: "Payment for Order #12345",
  redirectUri: new URL("https://example.com/payments"),
  statusCallbackUrl: new URL("https://example.com/api/callbacks/payment/status"),
  refundableFor: { days: 1 },
  expiresIn: { hours: 1 },
}

const authRes = await FIB.authenticate()
const { access_token } = await authRes.json()

const res = await FIB.createPayment(paymentInput, access_token)

This method returns a JSON response, that is the details of transaction that you just created, represented by Payment type:

{
  "paymentId": "9dfa724f-4784-4487-811b-63057b540503",
  "readableCode": "S3LE-NZ2S-ZNGF",
  "qrCode": "data:image/png,base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAI...",
  "validUntil": "2022-01-31T12:15:44.020920Z",
  "personalAppLink": "https://fib.iq/personal-app-link?paymentId=some-id",
  "businessAppLink": "https://fib.iq/business-app-link?paymentId=some-id",
  "corporateAppLink": "https://fib.iq/corporate-app-link?paymentId=some-id"
}
  • paymentId: a string indicating the id of the payment
  • readableCode: a 12-character alpha-numeric string used to generate the qrCode property.
  • qrCode: a URL-encoded PNG image that can be shown to the user to scan and pay the amount.
  • validUntil: An ISO-8601-formatted date-time string, representing a moment in time when the payment expires.
  • personalAppLink: a string representing the personal deep link that users can visit which automatically opens the payment details in the FIB app.
  • businessAppLink: a string representing the personal deep link that users can visit which automatically opens the payment details in the FIB app.
  • corporateAppLink: a string representing the personal deep link that users can visit which automatically opens the payment details in the FIB app.
TIP

Users can pay the amount either by scanning the QRCode, manually typing the readableCode or visiting the deep-links like personalAppLink, we recommend showing all 3 options to the user to make it more convenient for your users to fulfill the payment

Users might refresh your page, or close your application and come back, make sure you save the transaction details in your database as it contains information that can helpful to you or your customers later.


getPaymentStatus

When you generated a payment, you can use this method to retrieve information about the status of the payment, this provides details on when the payment is paid, or if its canceled then why and some other useful information:

import { FIB } from "./fib.js"

const authRes = await FIB.authenticate()
const { access_token } = await authRes.json()

const res = await FIB.getPaymentStatus(paymentId, accessToken)

cancelPayment

When a payment is created, you might want to cancel the payment for any reason, this can be done before he payment is fulfilled:

import { FIB } from "./fib.js"

const authRes = await FIB.authenticate()
const { access_token } = await authRes.json()

const res = await FIB.cancelPayment(paymentId, accessToken)

refundPayment

After a payment is fulfilled, it can be refunded depending on the refundableFor option you created the payment with:

import { FIB } from "./fib.js"

const authRes = await FIB.authenticate()
const { access_token } = await authRes.json()

const res = await FIB.refundPayment(paymentId, accessToken)

Types

PaymentInput

type PaymentInput = {
  amount: number
  description?: string
  redirectUri?: URL
  statusCallbackUrl?: URL
  expiresIn?: Duration
  refundableFor?: Duration
}

PaymentResponse

type PaymentResponse = {
  paymentId: string
  readableCode: string
  qrCode: string
  validUntil: string
  personalAppLink: string
  businessAppLink: string
  corporateAppLink: string
}

PaymentStatusResponse

type PaymentStatusResponse = {
  paymentId: string
  amount: MonetaryValue
  status: "UNPAID" | "DECLINED" | "PAID" | "REFUNDED" | "REFUND_REQUESTED"
  paidAt?: string
  decliningReason?: "PAYMENT_CANCELLATION" | "PAYMENT_EXPIRATION"
  declinedAt?: string
  paidBy?: { name: string; iban: string }
}

Error Handling

There are two types of errors you might want to watch out for:

  1. When the requests return a Response, but its not in 2xx range, in this case FIB backend returns an error message and some traceId, that we can inspect the request for you if the error is not expected.

    const res = await FIB.getPaymentStatus(paymentInput, accessToken)
    if(res.status !== 200){
      const { errors } = await res.json()
    }
    
  2. When the request fails with an Error, which might happen for several reasons, for example a NetworkError or other runtime exceptions.

    try{
      const res = await FIB.getPaymentStatus(paymentInput, accessToken)
      const { status } = await res.json()
    
      return status
    }catch(error){
      console.log("Something went wrong", error)
      return null
    }