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.

1import { MmgCheckoutUtil } from "mobile-money-sdk"; // Import the custom utility
2import express from "express";
3
4const app = express();
5
6// Initialize the Checkout Utility
7/**
8 process.env.* returns string | undefined — TypeScript will complain if you pass those directly to fields typed as string. The ! non-null assertion (or
9 runtime validation) is needed for publicKey, secretKey, merchantId, and clientId.
10**/
11 const checkoutUtil = new MmgCheckoutUtil({
12 environment: "Live", // or "Sandbox"
13 publicKey: process.env.MMG_PUBLIC_KEY!,
14 privateKey: process.env.MMG_PRIVATE_KEY,
15 });
16
17app.post("/api/checkout", async (req, res) => {
18 try {
19 // 2. Generate a unique Transaction ID for this order
20 const merchantTxnId = `ORD-${Date.now()}`;
21
22 // 3. Define the payload
23 const payload = {
24 secretKey: process.env.MMG_SECRET_KEY,
25 merchantId: process.env.MMG_MERCHANT_ID,
26 amount: "3000", // Amount in GYD
27 merchantTransactionId: merchantTxnId,
28 merchantName: "My Ecommerce Store",
29 productDescription: "Shopping Cart Checkout",
30 requestInitiationTime: Date.now().toString(),
31 };
32
33 // 4. Generate the Redirect URL
34 // The utility automatically encrypts the payload and appends the required query parameters
35 const redirectUrl = checkoutUtil.generateRedirectUrl(
36 payload,
37 process.env.MMG_CLIENT_ID
38 );
39
40 // 5. Send the URL to the frontend, or trigger the redirect directly
41 res.json({ redirectUrl: redirectUrl });
42
43 } catch (error) {
44 console.error("Failed to generate checkout URL", error);
45 res.status(500).json({ error: "Internal Server Error" });
46 }
47});