| 1 | import { MmgCheckoutUtil } from "mobile-money-sdk"; // Import the custom utility |
| 2 | import express from "express"; |
| 3 | |
| 4 | const 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 | |
| 17 | app.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 | }); |