Hosted Checkout Code Examples
Integrate DigetPay Hosted Checkout using your preferred programming language.
Your server creates a payment link, redirects the customer to the DigetPay Checkout page, then confirms the payment with the Status API. Webhooks notify you when a payment changes so you know when to check.
Apple Pay, Mada, 3-D Secure, and PCI compliance are fully handled by the DigetPay Hosted Checkout page. Your application only creates the payment session and redirects the customer.
PrerequisitesBefore you begin, make sure you have completed:
- A merchant account with access to the Merchant Dashboard (pay.digetpay.com)
- Your Test API Key (
x-api-key). See API Modes & Credentials- One of the supported languages:
- PHP 8+
- Node.js 18+
- Python 3.10+
- Java 17+
The API base URL is
https://api.digetpay.com/v1for both Test and Live. Your API key decides the mode.
ImportantThe Hosted Checkout endpoint is:
POST /payment/checkout/intiateThe path is intentionally spelled intiate and should be used exactly as documented.
Never trust the Success URLA customer arriving at your
successUrldoes not guarantee payment success, and a webhook is only a notification.Always verify payment with the Transaction Status API.
Architecture
sequenceDiagram
autonumber
participant Browser as Customer Browser
participant Merchant as Your Server
participant API as DigetPay API
participant Checkout as DigetPay Checkout
Browser->>Merchant: Start checkout
Merchant->>API: Create Payment Link
API-->>Merchant: sessionId + redirectUrl
Merchant->>Browser: HTTP Redirect
Browser->>Checkout: Complete Payment
Checkout->>Browser: successUrl / failureUrl
Browser->>Merchant: Return with sessionId
Merchant->>API: Query Status using sessionId
API-->>Merchant: Transaction Status
opt Webhook configured
API->>Merchant: Payment notification
end
Merchant->>Merchant: Verify payment and update order
Integration Steps
Step 1 — Configuration
Use one API base URL and load the API key from the environment. Use your Test API Key for development and testing, and your Live API Key only in your live deployment.
<?php
return [
'api_base' => 'https://api.digetpay.com/v1',
// Test API Key in development/QA; Live API Key in your live deployment.
'api_key' => getenv('DIGETPAY_API_KEY') ?: '',
];.envDIGETPAY_API_KEY=your_test_api_key.envDIGETPAY_API_KEY=your_test_api_keyexport const config = {
// Test API Key in development/QA; Live API Key in your live deployment.
apiKey: process.env.DIGETPAY_API_KEY,
apiBase: "https://api.digetpay.com/v1"
};.envDIGETPAY_API_KEY=your_test_api_keyimport os
api_base = "https://api.digetpay.com/v1"
# Test API Key in development/QA; Live API Key in your live deployment.
api_key = os.getenv("DIGETPAY_API_KEY")public final class DigetPayConfig {
private static final String API_BASE = "https://api.digetpay.com/v1";
public static String apiBase() {
return API_BASE;
}
// Test API Key in development/QA; Live API Key in your live deployment.
public static String apiKey() {
return System.getenv("DIGETPAY_API_KEY");
}
}Step 2 — API Client
$client = new DigetPayClient($config);The client should expose:
- createPaymentLink()
- getTransactionStatus()
- processRefund()
export function createPaymentLink(payload){
return request("POST","/payment/checkout/intiate",payload);
}
export function getTransactionStatus(sessionId) {
return request("GET", `/payment/checkout/status?sessionId=${sessionId}`);
}
export function processRefund(transactionId,amount){
return request("POST","/payment/refund",{
transactionId,
amount
});
}def create_payment_link(payload):
...
def get_transaction_status(session_id):
...
def process_refund(transaction_id, amount):
...client.createPaymentLink(payload);
client.getTransactionStatus(sessionId);
client.processRefund(transactionId, amount);
Status API IdentifierFor Hosted Checkout, use the stored session ID when querying the transaction status.
The Status API endpoint is:
GET /payment/checkout/status?sessionId=${sessionId}The response contains the Gateway Transaction ID, which should be stored in your database for future operations such as refunds.
Step 3 — Create Payment Link & Redirect
Create a payment session, save the returned session ID, then redirect the customer to the redirectUrl returned by the API. Use it exactly as returned; do not build the checkout URL yourself.
<?php
require_once __DIR__ . '/../src/DigetPayClient.php';
$config = require __DIR__ . '/../config/digetpay.php';
$client = new DigetPayClient($config);
$orderId = 'ORD-' . time();
$session = $client->createPaymentLink([
'merchantOrderId' => $orderId,
'amount' => 10.00,
'currency' => 'SAR',
'customerName' => 'Ahmed Ali',
'customerEmail' => '[email protected]',
'customerPhone' => '501223324',
'successUrl' => 'https://yourstore.com/checkout/success',
'failureUrl' => 'https://yourstore.com/checkout/failure'
]);
// Save session ID before redirecting
// saveSession($orderId, $session['id']);
header('Location: ' . $session['redirectUrl']);
exit;router.get("/checkout", async (req, res) => {
const session = await createPaymentLink({
merchantOrderId: `ORD-${Date.now()}`,
amount: 10,
currency: "SAR",
customerName: "Ahmed Ali",
customerEmail: "[email protected]",
customerPhone: "501223324",
successUrl: "https://yourstore.com/checkout/success",
failureUrl: "https://yourstore.com/checkout/failure"
});
// Store session.id before redirect
res.redirect(session.redirectUrl);
});@checkout.route("/checkout")
def checkout():
session = create_payment_link({
"merchantOrderId": f"ORD-{int(time.time())}",
"amount":10,
"currency":"SAR",
"customerName":"Ahmed Ali",
"customerEmail":"[email protected]",
"customerPhone":"501223324",
"successUrl":"https://yourstore.com/checkout/success",
"failureUrl":"https://yourstore.com/checkout/failure"
})
# Save session["id"]
return redirect(session["redirectUrl"])Map<String,Object> session = client.createPaymentLink(
Map.of(
"merchantOrderId","ORD-"+System.currentTimeMillis(),
"amount",10.00,
"currency","SAR",
"customerName","Ahmed Ali",
"customerEmail","[email protected]",
"customerPhone","501223324",
"successUrl","https://yourstore.com/checkout/success",
"failureUrl","https://yourstore.com/checkout/failure"
)
);
// Save session id
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create((String)session.get("redirectUrl")))
.build();
Apple PayNo additional code is required.
Apple Pay automatically appears on the DigetPay Hosted Checkout page when:
- The customer's device supports Apple Pay.
- Safari is being used.
customerPhoneis included in the request.
Step 4 — Handle Return URL
After the customer completes payment, DigetPay redirects the browser back to your application.
Important: Returning to the Success URL does not confirm payment. Always verify the transaction with the Transaction Status API.
<?php
$sessionId = $_GET["sessionId"] ?? null;
if (!$sessionId) {
http_response_code(400);
exit("Missing sessionId");
}
// Retrieve your order using sessionId
// Call Status API
echo "Processing payment...";router.get("/checkout/success",(req,res)=>{
const sessionId = req.query.sessionId;
// Lookup order
// Query Status API
res.send("Processing payment...");
});@checkout.route("/checkout/success")
def success():
session_id = request.args.get("sessionId")
# Lookup order
# Query Status API
return "Processing payment..."@GetMapping("/checkout/success")
public String success(
@RequestParam(required=false)
String sessionId){
// Lookup order
// Query Status API
return "Processing payment...";
}
Never Trust the RedirectA customer reaching the Success URL only means they returned from the checkout page.
The payment might still be:
- Pending
- Failed
- Cancelled
- Expired
Only mark the order as paid after a successful Status API response.
Step 5 — Confirm Payment
After the customer returns to your website, verify the payment using the Transaction Status API. Do not rely on the redirect URL or a webhook alone.
<?php
require_once __DIR__ . '/../src/DigetPayClient.php';
$config = require __DIR__ . '/../config/digetpay.php';
$client = new DigetPayClient($config);
// Retrieve the session ID from your database
$sessionId = 'stored-session-id';
$response = $client->getTransactionStatus($sessionId);
$content = $response['data']['content'][0] ?? null;
if ($content && $content['transactionStatus'] === 'SUCCESS') {
$gatewayTransactionId = $content['id'];
// Mark order as paid
// Save gatewayTransactionId for refunds
} elseif ($content && $content['transactionStatus'] === 'PENDING') {
// Payment is still processing
} else {
// Payment failed
}const response = await getTransactionStatus(sessionId);
const transaction = response?.data?.content?.[0];
if (transaction?.transactionStatus === "SUCCESS") {
const gatewayTransactionId = transaction.id;
// Mark order as paid
}
else if (transaction?.transactionStatus === "PENDING"){
// Still processing
}
else{
// Failed
}response = get_transaction_status(session_id)
transaction = response.get("data",{}).get("content",[{}])[0]
if transaction.get("transactionStatus") == "SUCCESS":
gateway_transaction_id = transaction["id"]
# Mark order paid
elif transaction.get("transactionStatus") == "PENDING":
# Still processing
pass
else:
# Failed
passMap<String,Object> response =
client.getTransactionStatus(sessionId);
Map<String,Object> transaction =
(Map<String,Object>)
((List<?>)((Map<?,?>)response.get("data"))
.get("content")).get(0);
String status =
(String)transaction.get("transactionStatus");
if("SUCCESS".equals(status)){
String gatewayTransactionId =
(String)transaction.get("id");
// Mark order paid
}
Successful PaymentWhen the payment status is SUCCESS:
- Update the order status.
- Store the Gateway Transaction ID.
- Send the customer confirmation.
- Trigger fulfillment.
The Gateway Transaction ID is required later for refunds.
Step 6 — Receive Webhooks
Webhooks are the recommended way to be notified automatically when a payment status changes. A webhook is a notification, not proof of payment: after you receive one, confirm the payment with the Status API before updating the order.
DigetPay sends HTTP POST requests to your configured webhook endpoint whenever a payment status changes. Test Mode and Live Mode use separate webhook configurations.
<?php
$raw = file_get_contents("php://input");
$payload = json_decode($raw,true);
http_response_code(200);
echo "OK";
$transactionId = $payload["transactionId"] ?? null;
$orderId = $payload["orderId"] ?? null;
$status = $payload["status"] ?? null;
// Check idempotency
// Do not trust the payload alone:
// confirm the payment with the Status API
// Update order only after the Status API confirms SUCCESSapp.post(
"/webhooks/digetpay",
express.raw({type:"application/json"}),
(req,res)=>{
const payload = JSON.parse(req.body.toString());
res.status(200).send("OK");
const{
transactionId,
orderId,
status,
type
}=payload;
// Check idempotency
// Do not trust the payload alone:
// confirm the payment with the Status API
// Update order only after the Status API confirms SUCCESS
});@app.route("/webhooks/digetpay",methods=["POST"])
def webhook():
payload = request.get_json(force=True)
transaction_id = payload.get("transactionId")
order_id = payload.get("orderId")
status = payload.get("status")
event_type = payload.get("type")
# Check idempotency
# Do not trust the payload alone:
# confirm the payment with the Status API
# Update order only after the Status API confirms SUCCESS
return "OK",200@PostMapping("/webhooks/digetpay")
public ResponseEntity<String> webhook(
@RequestBody Map<String,Object> payload){
String transactionId =
(String)payload.get("transactionId");
String orderId =
(String)payload.get("orderId");
String status =
(String)payload.get("status");
String type =
(String)payload.get("type");
// Check idempotency
// Do not trust the payload alone:
// confirm the payment with the Status API
// Update order only after the Status API confirms SUCCESS
return ResponseEntity.ok("OK");
}Webhook Best Practices
Implement IdempotencyDigetPay may retry webhook delivery.
Always deduplicate events using:
transactionIdtypebefore updating your database.
Respond ImmediatelyReturn HTTP 200 OK within a few seconds.
Heavy processing such as:
- Sending emails
- Updating inventory
- ERP synchronization
- Invoice generation
should happen asynchronously.
Recommended Payment Flow
- Customer completes payment.
- Customer returns to your Success URL, and DigetPay sends a webhook notification.
- Verify payment using the Status API.
- Update your database (idempotently).
- Complete order fulfillment.
This approach provides the highest reliability in Live Mode.
Step 7 — Process Refund
After a successful payment, you can issue either a full or partial refund using the Gateway Transaction ID returned by the Status API.
The Gateway Transaction ID is available in the payment confirmation response (
data.content[0].id). Store this value in your database for future refund requests.
<?php
require_once __DIR__ . '/../src/DigetPayClient.php';
$config = require __DIR__ . '/../config/digetpay.php';
$client = new DigetPayClient($config);
$gatewayTransactionId = "2232e99b-0257-47d5-bbfd-022c8951767f";
$amount = 5.00;
$result = $client->processRefund(
$gatewayTransactionId,
$amount
);
// Update your order statusimport { processRefund } from "../src/digetpayClient.js";
await processRefund(
"2232e99b-0257-47d5-bbfd-022c8951767f",
5.00
);
// Update your orderfrom digetpay_client import process_refund
process_refund(
"2232e99b-0257-47d5-bbfd-022c8951767f",
5.00
)
# Update your orderclient.processRefund(
"2232e99b-0257-47d5-bbfd-022c8951767f",
5.00
);
// Update your orderTest Mode vs Live Mode
| Setting | Test Mode | Live Mode |
|---|---|---|
| API Base URL | https://api.digetpay.com/v1 | https://api.digetpay.com/v1 |
| Dashboard | https://pay.digetpay.com/ | https://pay.digetpay.com/ |
| API Key | Test API Key | Live API Key |
| Webhooks | Test Webhook Configuration | Live Webhook Configuration |
To go live, switch your API Key and webhook configuration. The API Base URL does not change.
What DigetPay Handles
One of the main advantages of Hosted Checkout is that DigetPay manages all payment UI and PCI-sensitive functionality for you.
| Feature | Handled By |
|---|---|
| Payment Form | DigetPay Checkout |
| Card Validation | DigetPay Checkout |
| Apple Pay | DigetPay Checkout |
| Mada | DigetPay Checkout |
| 3-D Secure Authentication | DigetPay Checkout |
| PCI DSS Compliance | DigetPay Infrastructure |
| Card Data Storage | DigetPay Infrastructure |
Your application only needs to:
- Create the payment link.
- Redirect the customer.
- Verify payment.
- Handle webhooks.
- Process refunds.
Go-Live Checklist
Before requesting go-live approval, verify the following:
- ✅ End-to-end payment tested in Test Mode with your Test API Key and Test Cards.
- ✅ Success URL configured.
- ✅ Failure URL configured.
- ✅ Test and Live webhook URLs configured separately.
- ✅ Status API implemented.
- ✅ Webhook processing implemented.
- ✅ Duplicate webhook protection implemented.
- ✅ Refund flow tested.
- ✅ Error handling completed.
- ✅ Logging enabled.
- ✅ Live API Key received.
Ready to Go LiveOnce every item above has been completed successfully, your Hosted Checkout integration is ready to switch to your Live API Key.
Integration Flow Summary
flowchart LR A[Create Payment Link] -->B[Redirect Customer] B-->C[Customer Pays] C-->D[Return to Success URL] D-->E[Query Status API] C-->F[Receive Webhook] F-->E E-->G[Verify Payment] G-->H[Mark Order Paid] H-->I[Future Refunds]
Related Documentation
Updated about 2 months ago

