Vendor UI: Invoice Component

Implementation Steps

  1. Authorization
  2. Installation
  3. Implementation of Invoice Component on your webpage
  4. Optional: Reset the Invoice Component on the webpage
  5. DOM EventListeners

1. Authorization

In order to load the Invoice Component in your platform, an authorized API call is needed in your backend with defined scopes and a vendor ID (if applicable) to generate the access token.

Generate an access token

Below is an example of the payload for generating an access token:

`curl -X POST "https://sandbox.unipaas.com/platform/authorize"
2  -H  "accept: application/json"
3  -H  "Authorization: Bearer <PLATFORM_SECRET_KEY>"
4  -H  "Content-Type: application/json"
5  --data-raw '{
6      "scopes": ["portal_read","portal_write","onboarding_write","invoice_read","invoice_write"],
7      "vendorId": "{vendorId}"
8   }'`
const request = require("request");
const url = "https://sandbox.unipaas.com/platform/authorize";
const secretKey = "<PLATFORM_SECRET_KEY>";
const vendorId = "<YOUR_VENDOR_ID>"; 
const scopes = ["portal_read", "portal_write", "onboarding_write" , "invoice_read" , "invoice_write"]

const options = {
    url,
    method: "POST",
    headers: {
        "Accept": "application/json",
        "Authorization": `Bearer ${secretKey}`,
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        scopes,
        vendorId
    })
};

request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log(response.body);
});
VerbPOST
Environmentsandbox
URLhttps://sandbox.unipaas.com/platform/authorize
NameTypeRequiredDescription
scopesstringYESThe scopes portal_read, portal_write, onboarding_write, invoice_read and invoice_write included in this API request example, determine the level of access required to perform specific actions, similar to GET and POST methods
vendorReferencestringYESThe user id on your system
vendorIdstringNOA vendor ID is a unique identifier for the vendor requesting API access.
You can obtain a vendor ID when you create a vendor on your platform

Note! If you don't have a vendor ID, do not include the parameter in your API request, then a public access token will be issued

📘

Note!

If you don't have a vendor ID, do not include the parameter in your API request, then a public access token will be issued.

Response example

{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsib25ib2FyZGluZ193cml0ZSIsInBheW91dF93cml0ZSIsImxpbmtfd3JpdGUiLCJvbmJvYXJkaW5nX3dyaXRlIiwibm90aWZpY2F0aW9uX3dyaXRlIiwiY29uZmlnX3JlYWQiLCJkaXJlY3RfZGViaXRfd3JpdGUiLCJld2FsbGV0X3JlYWQiLCJwdWJsaWNfY29uZmlnX3JlYWQiLCJsaW5rX3JlYWQiLCJvbmJvYXJkaW5nX3JlYWQiLCJub3RpZmljYXRpb25fcmVhZCIsImNvbmZpZ19yZWFkIl0sInZlbmRvcklkIjoiNjNkN2E2Njk4NGFkZDc5YWU2YmFmZDg3IiwibWVyY2hhbnRJZCI6IjYxZTZlOTdmZjEyNDJiODIwYzlkNWM4MSIsImVudiI6ImRldiIsImlhdCI6MTY4MTg1MTQ5MCwiZXhwIjoxNjgxODUzMjkwfQ.q5dCR3zfuEWCTG8HdvfEtlY7BmHxvJL0PFinlJSe8uQ",
  "expiresIn": 3600,
    "scopes": [
        "onboarding_write",
        "ewallet_write",
        "payout_write",
        "link_write",
        "onboarding_write",
        "notification_write",
        "config_read",
        "direct_debit_write",
        "checkout_create",
        "ewallet_read",
        "public_config_read",
        "link_read",
        "onboarding_read",
        "notification_read",
        "config_read",
        "public_config_read",
        "onboarding_read",
        "config_read",
        "notification_read",
        "public_config_read",
        "onboarding_write",
        "direct_debit_write"
    ],
  "vendorId": "{vendorId}",
  "merchantId": "{merchantId}",
  "merchantName": "{merchantName}",
  "env": "sandbox"
}
NameTypeDescription
accessTokenstringAccess token for the UI Web-Embeds
expiresInstringTime until the access token expires (in seconds)
scopesstringList of permissions granted for the access token
vendorIdstringUnique identifier for the vendor requesting access
merchantIdstringUnique identifier for the platform associated with the vendor
envstringThe environment in which the access token was issued

📘

This access token is valid for one hour, and it will be automatically refreshed whenever a UI Web-Embed communicates with the UNIPaaS servers.

Scopes

NameDescription
portal_readGrants all GET permissions required for using UI Web-Embeds on your platform
portal_writeGrants all POST permissions required for using UI Web-Embeds on your platform
onboarding_writeGrants specific POST permissions required for using Onboarding UI Web-Embeds on your platform

2. Installation

Script tag

Start with placing the following script tag element inside of the <head> of your HTML page:

<script type="application/javascript" src="https://cdn.unipaas.com/embedded-ui.js"></script>

This script tag loads the JavaScript code that provides the functionality for implementing UNIPaaS UI Web-Embeds on a webpage. When the script is loaded and executed, it will create an object in the memory that contains methods for instantiating and interacting with the UI Web-Embeds.

General configuration

Place the following script tag element below the closing </body> tag of your HTML page.
This script is used to initialize and configure UNIPaaS UI Web-Embeds on a web page.

<script type="text/javascript">
  const config_general = {
    paymentsEnabled: true,
    theme: { 
        colors: { 
            primaryColor: "#2F80ED", 
            secondaryColor: "#687B97", 
            accentTextColor: "#2F80ED", 
            primaryButtonColor: "#2F80ED" 
        },
        fontFamily: "inherit",
        boxShadow: "0px 3px 15px rgba(27, 79, 162, 0.11)" 
    }
  }
    const components = unipaas.components("<accessToken>", config_general);
</script>
NameTypeRequiredDescription
paymentsEnabledbooleanYESIndicates whether the UNIPaaS-powered embedded payments are enabled as the default payment provider for the vendor associated with the API request

If set to true, it means that the UNIPaaS-powered embedded payments are available for use

If set to false, it means that the vendor has chosen another payment provider/no online payments as a default option

Theme

Theme customisation allows to match the visual design of the components with your product.

NameTypeDescription
colors.primaryColorstringRepresents the primary color used for UI Web-Embeds
colors.secondaryColorstringRepresents the secondary color used for UI Web-Embeds
colors.accentTextColorstringRepresents the font color used for headers of UI Web-Embeds
colors.primaryButtonColorstringRepresents the font color used for primary buttons of UI Web-Embeds
fontFamilystringRepresents the font family used for UI Web-Embeds
Please use inherit to align the font family to the one used in your platform
boxShadowstringRepresents the box shadow applied to UI Web-Embeds, used to create a shadow effect

3. Implementation of Invoice Component on your webpage

Invoice Component should be implemented within 3 types of pages:

  1. New sales invoice - typically includes fields for inputting customer information, item descriptions, prices, and other relevant details related to the sales invoice creation process.
  2. Edit sales invoice - typically includes fields for modifying an existing sales invoice information, item descriptions, prices, and other relevant details related to the sales invoice.
  3. View sales invoice - typically includes fields for viewing an existing sales invoice information.

📘

Note!

Please note that when mounting a component using a selector, the component should not be mounted more than once per selector. Mounting a component more than once can lead to unexpected behaviour and issues.

To avoid this, make sure to check whether the component has already been mounted before calling the mount method.

📘

Note!

Allocate the minimal space for this component as follows:
Width - 475 pixels
Height - 250 pixels

New sales invoice page

Step 1: Create a container

Place the following div tag element inside the <body> tag of your HTML page.
Make sure to assign a unique ID to the container so that it can be easily identified and accessed.

<div id="invoice"></div>

Step 2: Create and mount an instance below the container

Place the following script tag element below the closing </body> tag of your HTML page.

Create an instance of it and mount it to the container DOM node in your page. This should be done after container (the previous div) has finished loading.

<script type="text/javascript">
  const config_invoice = {
    mode: 'create',            //Mandatory
    customer: {
      reference: '1234567',    //Mandatory
      name: 'John Doe',        //Mandatory
      email: '[email protected]',
   },
    invoice: {
      reference: 'INV-123',     //Mandatory
    }
  }; // UNIPaaS Components Invoice config type
  const invoice = components.create("invoice", config_invoice);
  invoice.mount("#invoice")
</script>
NameTypeRequiredDescription
modestringYESIndicates the type of the invoice page - is the user creating a new invoice, editing or viewing an existing invoice
For creating a new sales invoice mode 'create' is required
customer.referencestringYESRepresents the unique identifier for the customer associated with the invoice.
customer.namestringYESRepresents the name of the customer associated with the invoice.
customer.emailstringNORepresents the email address of the customer associated with the invoice.
invoice.referencestringYESRepresents the unique identifier for the invoice.

Step 3: Make API call from backend:

Make a POST/platform/vendors/{vendorId}/invoices request from your backend when the invoice is saved on your system with the following parameters.

The invoice object

{
  "reference": "INV-1234",         // Mandatory
  "currency": "GBP",
  "totalAmount": 99.5,
  "vatAmount": 19.9,
  "dueDate": "2022-12-12T08:42:52.933Z",
  "paymentStatus": "unpaid",
  "totalPaid": 0,
  "customer": {
    "reference": "1234",           // Mandatory
    "email": "[email protected]",
    "name": "Kevin Malone"         // Mandatory
  },
  "lineItems": [
    {
      "description": "line 1",
      "unitPrice": 10.6,
      "quantity": 3
    },
    {
      "description": "line 2",
      "unitPrice": 19.3,
      "quantity": 1
    }
  ],
  "isRecurring": true,
  "subscriptionId": "sub-123",
  "external":false,
  "batchId": "batch-777",
  "publicUrl": "http://yourcompany.com/invoice.pdf",
  "invoiceObject": {}
}

Attributes

NameIs RequiredTypeDescription
referenceYesStringThe invoice number on your system.
currencyYesISO 4217The currency of the invoice
totalAmountYesNumberThe total invoice amount
vatAmountNoNumberThe total VAT amount for the invoice (can be 0).
If not provided, will be set to 0 by default.
dueDateYesDateThe invoice due date.
totalPaidNoNumberThe total amount paid so far on this invoice.
If not provided, will be set to 0 by default.
batchIdNoStringThe ID of the batch that this invoice was included in.
publicUrlNoStringA public URL to the invoice PDF version.
lineItemsYesArray Line item object - see table below.
customerYesObjectCustomer object - see table below.
paymentStatusYesEnumCurrent invoice payment status:
Unpaid = unpaid
Paid = paid
Partially Paid = partially_paid
Refunded = refunded
PartiallyRefunded = partially_refunded
paymentMethodsNoArray, EnumStates which payment methods will be available for this specific invoice.
Note: If Direct Debit is selected, the invoice cannot be paid with UNIPaaS in any other method.

Available Payment Methods:
creaditCard
bankTransfer
directDebit
offlineBankTransfer
paypal

Important - when the Invoice UI Web-Embed is not implemented (e.g., in the recurring payment flow), it is critical to send this parameter with directDebit for every recurring payment if Direct Debit is to be used to collect the payment.

*Based on platform configuration
invoiceObjectNoObjectThe invoice object in its original form as created on your platform.
isRecurringYesBooleanIndicates if this invoice is a recurring one.
externalNoBooleanIndicates if this invoice was paid using external (non UNIPaaS). payment method. If value is set to 'false' it is an indication that an invoice paid with UNIPaaS.
Default value is set to 'false'.
subscriptionIdNoStringThe recurring invoice subscription identifier.

lineItem attributes:

NameIs RequiredTypeDescription
descriptionYesStringA description for a specific line item
amountYesNumberA price of a unit for a specific line item
quantityYesNumberThe quantity of a unit for a specific line item

customer attributes:

NameIs RequiredTypeDescription
referenceYesStringPlatform customer identifier.
nameYesStringThe customer full name.
idNoStringUNIPaaS customer identifier.
emailNoStringThe customer email address.

Response example

{
    "id": "6539271a23ebdaa55bae0e4f",          // store and use this ID incase of invoice edit
    "merchantId": "6440ca5ec6f5484043645595",
    "vendorId": "64b2acf5e59cc36181291f8d",
    "currency": "GBP",
    "totalAmount": 99.5,
    "totalPaid": 0,
    "vatAmount": 19.9,
    "reference": "INV-1234",
    "publicUrl": "http://yourcompany.com/invoice.pdf",
    "invoiceObject": {},
    "subscriptionId": "sub-123",
    "isRecurring": true,
    "batchId": "batch-777",
    "customer": {
        "reference": "1234567",
        "email": "[email protected]",
        "name": "orel reast"
    },
    "lineItems": [
        {
            "description": "line 1",
            "unitPrice": 10.6,
            "quantity": 3
        },
        {
            "description": "line 2",
            "unitPrice": 19.3,
            "quantity": 1
        }
    ],
    "paymentStatus": "unpaid",
    "dueDate": "2022-12-12T08:42:52.933Z",
    "paymentMethods": [
        "bankTransfer",
        "creditCard"
    ],
    "external": false,
    "authorizationId": "65392719bd672b26f20d53ca",
    "signedLinkId": "RGJ4_2wLWr",
    "checkoutLink": "https://sandbox-checkout.unipaas.com/sB8qYUCHWO/",
	  "sessionToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjaGFudElkIjoiNjJmYzk5YjI0YzcyOGIzZjAyZmM2MzRmIiwibWVyY2hhbnROYW1lIjoiTmV3IFBsYXRmb3JtIiwiYW1vdW50IjoxMCwiY3VycmVuY3kiOiJHQlAiLCJlbWFpbCI6InVzZXJAdGVzdC5jb20iLCJjb3VudHJ5IjoiR0IiLCJzZWxsZXJJZCI6IjY1MWU2ODRhZDAwNjg5MWIzNWJkZGQ2OCIsInZlbmRvcklkIjoiNjUxZTY4NGFkMDA2ODkxYjM1YmRkZDY4IiwicGhvbmUiOiIrNDQxNjE0OTYwMjU1Iiwic2NvcGVzIjpbIndlYnNka19hY2Nlc3MiLCJkaXJlY3RfZGViaXRfcmVhZCJdLCJpc1JlY3VycmluZyI6ZmFsc2UsImVudiI6ImxvY2FsIiwicGF5bWVudExpbmtJZCI6Ik0zc09laFU1ZEMiLCJpYXQiOjE3MjcwOTc5NTMsImV4cCI6MTcyNzEwMTU1M30.mR_rA3cF5UTANKHcgPVyyfidXg8JieBg_otX6Iz_5V8",
    "createdAt": "2023-10-25T14:32:58.566Z",
    "updatedAt": "2023-10-25T14:32:58.566Z"
}
NameTypeDescription
idStringThe value you obtained in the response to POST request, serves to identify this invoice in Unipaas
checkoutLinkStringThe checkout link for the invoice, which includes the available payment methods for buyer.

Update invoice payment method

In order to update the payment method for an invoice, the user simply changes it in the Invoice component and it changes it in the checkout page.

Update invoice method

When a customer is selected during invoice creation or editing, it is important to use the invoice.update method. This will let Unipaas know which payment options are available for the selected customer, and will change the invoice component in real time to reflect this.

It should be used while users are filling out the mandatory invoice fields using your platform's UI, before they save a new invoice.
Please call the update method with the customer data (you can call this method multiple times with the customer object or with the invoice object separately).

invoice.update({
   customer: {
      reference: '1234567', //Mandatory
      name: 'John Doe',     //Mandatory
      email: '[email protected]',
   },
   invoice: {
      reference: 'INV-123', //Mandatory
   }
})
NameTypeRequiredDescription
customer.referencestringYESRepresents the unique identifier for the customer associated with the invoice.
customer.namestringYESRepresents the name of the customer associated with the invoice.
customer.emailstringNORepresents the email address of the customer associated with the invoice.
invoice.referencestringNORepresents the unique identifier for the invoice.

📘

Important!

Whenever there is a customer selected, you should update the invoice. This applies to when a customer is changed (customer A was selected and now customer B is selected) as well as if there is a default customer selection (customer C is selected by default when the invoice page loads)

Edit & View Sales Invoice

Step 1: Create a container

Place the following div tag element inside the <body> tag of your HTML page.
Make sure to assign a unique ID to the container so that it can be easily identified and accessed.

<div id="invoice"></div>

Step 2: Create and mount an instance below the container

Place the following script tag element below the closing </body> tag of your HTML page.

Create an instance of it and mount it to the container DOM node in your page. This should be done after container (the previous div) has finished loading.

<script type="text/javascript">
  const config_invoice = {
    mode: 'edit',                //Mandatory
    customer: {
      reference: '1234567',      //Mandatory
      name: 'John Doe',          //Mandatory
      email: '[email protected]',
   },
   invoice: {
      reference: 'INV-123',      //Mandatory
   }
  }; 
  const invoice = components.create("invoice", config_invoice);
  invoice.mount("#invoice");
</script>
NameTypeRequiredDescription
modestringYESIndicates the type of the invoice page.
Is the user is creating a new invoice, editing or viewing an existing invoice.
For editing an existing invoice mode: 'edit' is required.
For viewing an existing invoice mode: 'view' is required.
customer.referencestringYESRepresents the unique identifier for the customer associated with the invoice.
customer.namestringYESRepresents the name of the customer associated with the invoice.
customer.emailstringNORepresents the email address of the customer associated with the invoice.
invoice.referencestringYESRepresents the unique identifier for the invoice.

Step 3: Make backend API call:

When an existing invoice has been edited, e.g. changes to the total amount or due date OR when an existing invoice has been fully or partially paid; use PATCH/vendors/{vendorId}/invoices/{invoiceId}

🚧

Flexible checkout modifications require the mandatory use of the PATCH request

If not implemented, vendors won't be able to make adjustments to the amount, due date, or invoice payment method

The following invoice parameters might affect the payment:

  • totalAmount
  • totalPaid
  • paymentMethods
  • paymentStatus
  • dueDate

The updated invoice object example

Only update the values that have been changed.

Example of an invoice payload which was subject to a partial payment of 60 GBP, leading to a change in the payment status, and the payment method was switched by user to Direct Debit.

{
  "id": "6391fd42a38e34b15b118d9b", // ID from POST/invoices response during invoice create
  "totalPaid": 60.0,
  "paymentStatus": "partially_paid",
  "paymentMethods":["directDebit"],
}

Attributes

NameIs RequiredTypeDescription
idYesStringThe value you obtained in the response to POST request, serves to identify this invoice in Unipaas
totalPaidNumberThe total amount paid so far on this invoice
paymentStatusEnumCurrent invoice payment status
paymentMethodsArray,
Enum
States which payment methods will be available for this specific invoice.

Available Payment Methods:
creaditCard
bankTransfer
directDebit
offlineBankTransfer
paypal

⚙️

The response for a PATCH request will be the same as that for a POST request

4. Optional: Reset the Invoice Component on the webpage

In case there is a need to reset the component (for example for a different vendor), you can use the script below.

<script type="text/javascript">
  components.reset({
		accessToken: "<newAccesstoken>"
	});
</script>

5. DOM Event Listeners

Invoice component fires DOM events to let you know of any user action taking place. Listen to the DOM events and refer to other areas of your platform, so you could act according to the user’s intent.

Create DOM event listeners

Place the following script tag element at the very bottom, below the closing </body> tag of your HTML page.

components.on("paymentsEnable",  (e) => {
  console.log("paymentsEnable event", e.detail);
});
components.on("startOnboarding",  (e) => {
  console.log("startOnboarding event", e.detail);
});
components.on("completeOnboarding",  (e) => {
  console.log("payPortal event", e.detail);
});
components.on("onboardingFinished",  (e) => {
  console.log("onboardingFinished event", e.detail);
});
components.on("paymentMethodChanged",  (e) => {
  console.log("paymentMethodChanged event", e.detail);
});

DOM events will be received in the following format, e.detail, and may include a payload:

invoicePage
{
invoiceId: "INV1234"
}

Handle DOM events

EventDescriptionActionUI Web-Embeds
startOnboardingThis event is triggered when a user expresses their intent to register with your UNIPaaS-powered embedded payments solution.

This event is applicable only to new users who have not yet started registration.
Redirect the user to the Create New Vendor flow on your platform

Learn how to create a vendor
Pay Portal, Notification, Invoice, Balance
completeOnboardingThis event is triggered when a user expresses their intent to complete registration with your UNIPaaS-powered embedded payments solution.Redirect the user to the UNIPaaS Embedded Onboarding Component / Hosted Onboarding link

Learn more about vendor onboarding
Pay Portal, Notification, Invoice, Balance
enablePaymentsThis event is triggered when a user expresses their intent to enable the UNIPaaS-powered embedded payments solution in your platform when it is disabledRedirect the user to the settings page in your platform, where they can enable the payment solution and set it as a default payment optionInvoice
paymentMethodChanged

Payload:
{paymentMethods: string[]}
This event is triggered when payment method changed by the user.

Example:
{paymentMethods: ["bankTransfer", "card"]}
Send this array when you create checkout.Invoice