Hosted Checkout — Python

Create payment link, redirect, confirm status, and refund using Python requests.

Complete Hosted Checkout flow in Python 3.10+. Your server creates a payment link, redirects the customer, then confirms payment server-side.

Prerequisites: Sandbox Setup, staging x-api-key, Python 3.10+ with requests installed.

The path is spelled /payment/checkout/intiate — not /session.

Never mark an order paid based only on arrival at successUrl. Always confirm via status API or webhook.


Architecture

sequenceDiagram
  participant Browser as Customer Browser
  participant Shop as Your Python Server
  participant API as DigetPay API
  participant Checkout as DigetPay Checkout

  Browser->>Shop: Checkout (order total)
  Shop->>API: POST /payment/checkout/intiate
  API-->>Shop: redirectUrl
  Shop->>Browser: HTTP 302 redirect
  Browser->>Checkout: Pay (card / Mada / Apple Pay)
  Checkout->>Browser: Redirect successUrl / failureUrl
  Browser->>Shop: Return to your site
  Shop->>API: GET /payment/checkout/status
  API-->>Shop: transactionStatus

Step 1 — Configuration

.env:

DIGETPAY_ENV=staging
DIGETPAY_API_KEY=your_fin_staging_key
# config/digetpay.py
import os

API_BASES = {
    "staging": "https://fin-api.digetpay.com/v1",
    "production": "https://api.digetpay.com/v1",
}

environment = os.getenv("DIGETPAY_ENV", "staging")
api_key = os.getenv("DIGETPAY_API_KEY", "")
api_base = API_BASES[environment]

if not api_key:
    raise RuntimeError("DIGETPAY_API_KEY is not set")

Step 2 — API client

# digetpay_client.py
import requests
from config.digetpay import api_base, api_key

HEADERS = {"Content-Type": "application/json", "x-api-key": api_key}


def _request(method: str, path: str, body: dict | None = None) -> dict:
    url = f"{api_base}{path}"
    resp = requests.request(method, url, headers=HEADERS, json=body, timeout=30)
    resp.raise_for_status()
    return resp.json()


def create_payment_link(payload: dict) -> dict:
    return _request("POST", "/payment/checkout/intiate", payload)


def get_transaction_status(gateway_transaction_id: str) -> dict:
    return _request("GET", f"/payment/checkout/status?id={gateway_transaction_id}")


def process_refund(transaction_id: str, amount: float) -> dict:
    return _request("POST", "/payment/refund", {"transactionId": transaction_id, "amount": amount})

Step 3 — Create payment link and redirect

Flask example:

# routes/checkout.py
from flask import Blueprint, redirect
from config.digetpay import environment
from digetpay_client import create_payment_link

checkout_bp = Blueprint("checkout", __name__)


@checkout_bp.route("/checkout")
def start_checkout():
    is_staging = environment == "staging"
    success_url = (
        "https://fin-admin.digetpay.com/pay/checkout/success"
        if is_staging
        else "https://yourstore.com/checkout/success"
    )
    failure_url = (
        "https://fin-admin.digetpay.com/pay/checkout/failure"
        if is_staging
        else "https://yourstore.com/checkout/failure"
    )

    session = create_payment_link({
        "merchantOrderId": f"ORD-{int(__import__('time').time())}",
        "amount": 10.0,
        "currency": "SAR",
        "customerName": "Ahmed Ali",
        "customerEmail": "[email protected]",
        "customerPhone": "501223324",
        "successUrl": success_url,
        "failureUrl": failure_url,
    })
    # Store session["id"] in your DB before redirect
    return redirect(session["redirectUrl"], code=302)

Apple Pay: DigetPay checkout displays Apple Pay when the customer uses Safari and customerPhone was sent. No additional Python code required — see Apple Pay on Hosted Checkout.


Step 4 — Handle return URLs

@checkout_bp.route("/checkout/success")
def checkout_success():
    session_id = request.args.get("sessionId")
    return "Processing your payment… We will confirm shortly."

Step 5 — Confirm payment

from digetpay_client import get_transaction_status

response = get_transaction_status("2232e99b-0257-47d5-bbfd-022c8951767f")
content = (response.get("data") or {}).get("content", [{}])[0]
if content.get("transactionStatus") == "SUCCESS":
    pass  # Mark order paid

See Query Transaction Status.


Step 6 — Webhook handler

@app.route("/webhooks/digetpay", methods=["POST"])
def digetpay_webhook():
    payload = request.get_json(force=True)
    # Idempotent update — skip if already processed
    return "OK", 200

Full details: Handle Webhooks, Verify Signatures.


Step 7 — Refund

from digetpay_client import process_refund

process_refund("2232e99b-0257-47d5-bbfd-022c8951767f", 5.0)

Process Refund guide →


Next steps


Did this page help you?