Generating the Payment URL

Generating the Payment URL

When a customer is ready to check out, your backend needs to construct a CheckoutTokenPayload, encrypt it using the MMG Public Key, and generate the final checkout URL. The SDK handles the RSA encryption and Base64-URL encoding for you.

Usage Example

Below is an example of how to generate the URL using Node.js and Express.

import { MmgCheckoutUtil } from "mobile-money-sdk"; // Import the custom utility
import express from "express";
const app = express();
// Initialize the Checkout Utility
/**
process.env.* returns string | undefined — TypeScript will complain if you pass those directly to fields typed as string. The ! non-null assertion (or
runtime validation) is needed for publicKey, secretKey, merchantId, and clientId.
**/
const checkoutUtil = new MmgCheckoutUtil({
environment: "Live", // or "Sandbox"
publicKey: process.env.MMG_PUBLIC_KEY!,
privateKey: process.env.MMG_PRIVATE_KEY,
});
app.post("/api/checkout", async (req, res) => {
try {
// 2. Generate a unique Transaction ID for this order
const merchantTxnId = `ORD-${Date.now()}`;
// 3. Define the payload
const payload = {
secretKey: process.env.MMG_SECRET_KEY,
merchantId: process.env.MMG_MERCHANT_ID,
amount: "3000", // Amount in GYD
merchantTransactionId: merchantTxnId,
merchantName: "My Ecommerce Store",
productDescription: "Shopping Cart Checkout",
requestInitiationTime: Date.now().toString(),
};
// 4. Generate the Redirect URL
// The utility automatically encrypts the payload and appends the required query parameters
const redirectUrl = checkoutUtil.generateRedirectUrl(
payload,
process.env.MMG_CLIENT_ID
);
// 5. Send the URL to the frontend, or trigger the redirect directly
res.json({ redirectUrl: redirectUrl });
} catch (error) {
console.error("Failed to generate checkout URL", error);
res.status(500).json({ error: "Internal Server Error" });
}
});