Medusa.js is an open-source headless commerce platform that aims to ease the e-commerce solution for merchants. Built with JavaScript, it provides a robust and extensible back-end for functionality customization. Medusa.js offers integration with some famous front-end frameworks like Next.js, React and Vue.js. Whether you are a developer or a business owner, Medusa.js helps to create a unique shopping experience that fits your needs.
In addition to the core functionality, Medusa.js also allows you to add in more custom functionality. This can be in the type of event subscriber, workflow and more. This is useful when you want to add new features. For example, you may want to send an order confirmation email to your customer once they have placed an order. As a merchant, you can do more to secure your online business store from any kind of fraud. This can be achieved with a fraud validation service to verify every purchase order precisely.
In this tutorial, we are going to demonstrate how to use the FraudLabs Pro Screen Order API to validate the order, and cancel the order if we determined that it is fraudulent. If you are interested to get more information about the API, you can always refer to its documentation.
Before we get started, make sure that you have a FraudLabs Pro API key with you. If you don’t, you can always register for a free API key to get started. This tutorial will also assume that you have already installed and set up the v2 of the Medusa.js in your machine. If you haven’t, the simplest way to get it is to follow their installation instructions in their documentation to get started.
Steps to use FraudLabs Pro API in Medusa.js
- In your Medusa.js back-end project directory, go to the src/ and create a new folder called subscribers if the folder does not exist. Then, create a new file called validate-order.ts, and inside the file, paste the following code into it:
import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"; import { sdk } from "../admin/lib/config"; export default async function orderPlacedHandler({ event: { data, name, metadata }, container, }: SubscriberArgs<{ id: string }>) { const logger = container.resolve("logger"); logger.info("Sending confirmation email..."); logger.info("Detected ID " + data.id); sdk.store.order.retrieve(data.id).then(({ order }) => { async function postPayload() { const payload = { key: process.env.FRAUDLABSPRO_API_KEY, first_name: order.shipping_address.first_name, last_name: order.shipping_address.last_name, bill_addr: order.billing_address.address_1, bill_city: order.billing_address.city, bill_state: order.billing_address.province, bill_country: order.billing_address.country_code, bill_zip_code: order.billing_address.postal_code, ship_last_name: order.shipping_address.last_name, ship_first_name: order.shipping_address.first_name, ship_addr: order.shipping_address.address_1, ship_city: order.shipping_address.city, ship_state: order.shipping_address.province, ship_country: order.shipping_address.country_code, ship_zip_code: order.shipping_address.postal_code, user_phone: order.shipping_address.phone, email: order.email, user_order_id: data.id, amount: order.subtotal, currency: order.currency_code, }; console.log(payload); try { const response = await fetch( "https://api.fraudlabspro.com/v2/order/screen", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), } ); if (!response.ok) { console.log(response); throw new Error(`HTTP error! status: ${response.status}`); } const jsondata = await response.json(); console.log("Response:", jsondata); console.log(jsondata.fraudlabspro_status); if (jsondata.fraudlabspro_status == "REJECT") { logger.info("Detected fraud order, cancelling now..."); sdk.admin.order.cancel(data.id).then(({ order }) => { console.log(order); }); } } catch (error) { console.error("Error posting payload:", error); } } postPayload(); }); } export const config: SubscriberConfig = { event: `order.placed`, };
- After that, go to the src/admin/ directory, and create a new folder called lib if the folder does not exist. Then, create a new file called config.ts, and paste the following contents into the file:
import Medusa from "@medusajs/js-sdk" export const sdk = new Medusa({ baseUrl: <your_medusa_host>, publishableKey: <your_medusa_publishablekey>, debug: process.env.NODE_ENV === "development", apiKey: <your_medusa_apikey>, auth: { type: "session", }, })
- The value of the publishableKey and apiKey can be created and found in your Medusa.js admin dashboard once login.
- Finally, add your FraudLabs Pro API key in your .env file like this:
FRAUDLABSPRO_API_KEY=YOUR_API_KEY
- Now the API shall be set up in your e-commerce site. Once the API detected any fraud order, you shall see the order had been cancelled in your admin dashboard, for example, here is how it may look like:
Fortify Your Business Against Fraud
Streamline your works with our fraud detection API now!