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.

import os
import time
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from mmg import MmgCheckoutUtil
from mmg.types import CheckoutTokenPayload
app = FastAPI()
checkout_util = MmgCheckoutUtil(
environment="Live", # or "Sandbox"
public_key=os.getenv("MMG_PUBLIC_KEY"),
private_key=os.getenv("MMG_PRIVATE_KEY"),
)
class CheckoutResponse(BaseModel):
redirectUrl: str
@app.post("/api/checkout", response_model=CheckoutResponse)
async def create_checkout():
try:
merchant_txn_id = f"ORD-{int(time.time() * 1000)}"
payload = CheckoutTokenPayload(
secret_key=os.getenv("MMG_SECRET_KEY"),
merchant_id=os.getenv("MMG_MERCHANT_ID"),
amount="3000", # GYD
merchant_transaction_id=merchant_txn_id,
merchant_name="My Ecommerce Store",
product_description="Shopping Cart Checkout",
request_initiation_time=str(int(time.time() * 1000)),
)
redirect_url = checkout_util.generate_redirect_url(
payload=payload,
client_id=os.getenv("MMG_CLIENT_ID"),
)
return {"redirectUrl": redirect_url}
except Exception as e:
print(f"Failed to generate checkout URL: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")