BeforeSend
This function takes a callback function as an argument. Before Open Elements sends the transaction to the backend api for processing, we can intercept the data to be passed using beforeSend
function. We can instruct Open Elements to do the one of the following:
- Proceed with the transaction with the original data
- Proceed with the transaction with modified data, such as adding value to the total, adding additional line items, fixing some address discrepancy, etc.
- Prevent the transaction from being sent and display an error message to the user
The structure of beforeSend
function (line 22):
let oe = new openElements('Mg2KYmzEEPn2Q4Kf', {
total: 2.50,
currency: "USD",
orderId: '[[email protected]](mailto:[email protected])()',
phoneCountryCode: "+1",
lineItems: [
{
productCode: "code001",
name: "Product001",
quantity: 1,
amount: 2.00,
},
{
productCode: "code002",
name: "Product002",
quantity: 2,
amount: 0.50,
},
]
});
oe.beforeSend(async (data) => {
const validationResult = await additionalValidation(data);
if (validationResult.success) {
return {
proceed: true,
data: {
...data,
total: 999
}
}
}
return {
proceed: false,
errorMessage: 'Validation error',
errorTitle: 'Error',
data
}
});
In the sample code above from line 22, we passed an async function to beforeSend
.
Inside the function we can get the data from Open Elements and perform other process such as sending the data to a backend API for additional validation (in example code).
We then check if the validation succeeded, we return an object with boolean
property proceed set to true to instruct Open Elements to proceed with the payment. We also update the total to 999 in the example code. Other properties can also be updated such as currency, phone number, email, line items, addresses.
In line 35, if the validation is not successful, we are returning an object with property proceed set to false to prevent Open Elements from sending the payment. We also set the error message and title, this will display a modal to the user.
Updated 4 months ago