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 FastAPI.

1 import os
2 import time
3 from fastapi import FastAPI, HTTPException
4 from pydantic import BaseModel
5
6 from mmg import MmgCheckoutUtil
7 from mmg.types import CheckoutTokenPayload
8
9 app = FastAPI()
10
11 checkout_util = MmgCheckoutUtil(
12 environment="Live", # or "Sandbox"
13 public_key=os.getenv("MMG_PUBLIC_KEY"),
14 private_key=os.getenv("MMG_PRIVATE_KEY"),
15 )
16
17
18 class CheckoutResponse(BaseModel):
19 redirectUrl: str
20
21
22 @app.post("/api/checkout", response_model=CheckoutResponse)
23 async def create_checkout():
24 try:
25 merchant_txn_id = f"ORD-{int(time.time() * 1000)}"
26
27 payload = CheckoutTokenPayload(
28 secret_key=os.getenv("MMG_SECRET_KEY"),
29 merchant_id=os.getenv("MMG_MERCHANT_ID"),
30 amount="3000", # GYD
31 merchant_transaction_id=merchant_txn_id,
32 merchant_name="My Ecommerce Store",
33 product_description="Shopping Cart Checkout",
34 request_initiation_time=str(int(time.time() * 1000)),
35 )
36
37 redirect_url = checkout_util.generate_redirect_url(
38 payload=payload,
39 client_id=os.getenv("MMG_CLIENT_ID"),
40 )
41
42 return {"redirectUrl": redirect_url}
43
44 except Exception as e:
45 print(f"Failed to generate checkout URL: {e}")
46 raise HTTPException(status_code=500, detail="Internal Server Error")