DigetPay for Flutter
Accept card, Apple Pay, and Tamara payments in your Flutter app.
DigetPay gives you two ways to get paid:
- Hosted checkout: one call opens DigetPay's secure payment page in a WebView, where the payer chooses card, Apple Pay, or Tamara. No payment data passes through your app, so your PCI scope stays small.
- Server-to-server (S2S) API: full control from your own UI. Card sales and authorizations, saved-card charges, Apple Pay, Tamara, refunds, and payment status.
Pure Dart, built on http and webview_flutter. There's no native code to
write or register.
await DigetPaySdk.checkout()
.setOrder(DigetPaySaleOrder(id: orderId, description: 'Coffee', currency: 'SAR', amount: 15))
.setPayer(payer)
.onTransactionSuccess((res) => print('Paid ✓ ${res.paymentDetails?.transactionId}'))
.onTransactionFailure((res) => print('Failed: ${res.declineReason ?? res.status}'))
.onDismiss(() => print('Payer cancelled'))
.start(context);
Contents
- Install
- Quick start
- Services at a glance
- Hosted checkout
- Server-to-server (S2S)
- Payment status
- Responses and errors
- Sensitive data
- Debug logging
- Example app
- Platform setup
- Security
- Upgrading from 0.5
Install
dependencies:
digetpay_plugin: ^1.0.2
flutter pub add digetpay_plugin
Quick start
Initialize the SDK once at startup, then call the static DigetPaySdk API
anywhere:
import 'package:digetpay_plugin/digetpay_plugin.dart';
DigetPaySdk.initialize(
apiKey: '<your-mobile-api-key>',
baseUrl: 'https://api.digetpay.com/v1', // production
// sandbox: kDigetPayDefaultBaseUrl (https://fin-api.digetpay.com/v1)
);
Every call before
initialize()throwsDigetPaySdkIsNotInitializedException. To switch environment or key at runtime, callinitialize()again.
Services at a glance
| Service | DigetPaySdk method |
Endpoint |
|---|---|---|
| Hosted checkout: card · Apple Pay · Tamara | checkout() |
POST /v1/payment/checkout/intiate |
| Checkout session's payment | getCheckoutSessionTransaction(sessionId) |
GET /v1/payment/checkout/{sessionId}/transaction |
| Card sale | sale(request) |
POST /v1/payment/s2s/sale |
| Card authorization (hold) | authorize(request) |
POST /v1/payment/s2s/sale · auth: "Y" |
| Refund | refundS2s(transactionId:, amount:) |
POST /v1/payment/s2s/refund |
| Saved-card charge | tokenizationSale(request) |
POST /v1/payment/s2s/tokenization/sale |
| Payment status | getPaymentStatus(id) |
GET /v1/payment/s2s/transaction/{transactionId} |
| Apple Pay | applePay(request) |
POST /v1/payment/s2s/sale · paymentMethod: "applepay" |
| Tamara (buy now, pay later) | tamaraSale(request) |
POST /v1/payment/s2s/sale · paymentMethod: "tamara" |
completePayment() finishes any S2S payment: it presents the 3-D Secure or
redirect page and resolves the final result. See
Completing 3-D Secure and redirects.
Hosted checkout
Recommended for most apps. checkout() creates a payment session and opens
DigetPay's hosted page in a WebView. There the payer chooses card, Apple
Pay, or Tamara and completes 3-D Secure. No payment data passes through
your app.
await DigetPaySdk.checkout()
.setOrder(DigetPaySaleOrder(
id: orderId, description: 'Coffee', currency: 'SAR', amount: 15))
.setPayer(DigetPayPayer(
firstName: 'Demo', lastName: 'User', address: 'Riyadh',
country: 'SA', city: 'Riyadh', zip: '00000',
email: 'demo@example.com', phone: '+966500000000'))
.onSessionCreated((sessionId) {
// Keep it to look the payment up later with getCheckoutSessionTransaction().
})
.onTransactionSuccess((res) {
final payment = res.paymentDetails; // status, ids, card, amounts…
})
.onTransactionFailure((res) {
// res.declineReason · res.status · res.errorCode
})
.onDismiss(() {
// The payer closed the page without paying.
})
.start(context);
Exactly one of the three result callbacks fires.
DigetPaySdk.checkout()…start(context)
│
├─ POST /v1/payment/checkout/intiate ─────────▶ { id, redirectUrl }
│
├─ WebView: hosted page (card · Apple Pay · Tamara · 3-D Secure)
│
├─ result page reached ─▶ GET /v1/payment/checkout/{id}/transaction
│ ├─ SUCCESS ─▶ onTransactionSuccess(res)
│ └─ otherwise ─▶ onTransactionFailure(res)
│
└─ payer backs out ─────────────▶ onDismiss()
- The status lookup decides the result, not the page URL. A gateway can
show
/successbriefly before settling on/failure, so the SDK always confirms with the session's transaction. - Return URLs are optional. By default the SDK uses built-in URLs that it
intercepts itself. Call
.setResultUrls(successUrl:, failureUrl:)only if your merchant account restricts return URLs. intiateis spelled that way on the backend. The SDK calls it verbatim.
Card sale
sale() charges a card collected in your own UI.
⚠️ PCI scope.
sale()sends the raw card number and CVV through your app, which widens your PCI-DSS scope. Prefer hosted checkout unless you have assessed that trade-off.
const successUrl = 'https://example.com/success';
const failureUrl = 'https://example.com/failure';
final response = await DigetPaySdk.sale(
SaleRequest(
orderId: orderId,
amount: 1,
currency: 'SAR',
saveToken: true, // optional — returns a reusable card token
customer: const Customer(
name: 'Demo User',
email: 'demo@example.com',
phone: '+966500000000',
),
successUrl: successUrl,
failureUrl: failureUrl,
card: const CardDto(
cardNumber: '5123450000000008',
cardHolder: 'Demo User',
cardExpiryMonth: '01',
cardExpiryYear: '2039',
cardCvv: '100',
),
),
);
// Run 3-D Secure and get the final result:
final completion = await DigetPaySdk.completePayment(
context, response, successUrl: successUrl, failureUrl: failureUrl,
);
- The integrity hash is automatic. The SDK computes the
hashthe backend requires from the customer email, card number, and your API key. SetSaleRequest.hashonly to override it. - Nothing sensitive is logged. The card number, CVV, hash, and API key never appear in logs.
saveToken: truesaves the card. The response'scard?.token(TKN-…) can be charged again withtokenizationSale().
Card authorization
authorize() places a hold on the card instead of charging it. It takes
the same SaleRequest as sale() and sends auth: "Y":
final response = await DigetPaySdk.authorize(request);
print(response.action); // "AUTH"
final completion = await DigetPaySdk.completePayment(
context, response, successUrl: successUrl, failureUrl: failureUrl,
);
Completing 3-D Secure and redirects
Most S2S payments aren't final in the first response. It comes back
PENDING with either a 3-D Secure page (response.html) or a provider page
(response.redirectUrl, e.g. Tamara). completePayment() handles both:
- It opens the page in a WebView.
- It waits for your success or failure URL.
- It confirms the result with
getPaymentStatus().
final completion = await DigetPaySdk.completePayment(
context,
response,
successUrl: successUrl, // the same URLs you sent in the request
failureUrl: failureUrl,
);
final message = switch (completion.outcome) {
PaymentOutcome.approved => 'Paid — fulfil the order',
PaymentOutcome.declined => 'Failed, declined or cancelled',
PaymentOutcome.pending => 'Not final yet — check getPaymentStatus() later',
PaymentOutcome.dismissed => 'The payer closed the page',
};
final payment = completion.details; // PaymentDetails
It works the same for sale(), authorize(), tokenizationSale(),
applePay(), and tamaraSale(). If no page is needed (e.g. an instant
saved-card charge), it resolves straight from the response.
Refunds
Refund an S2S payment in full or in part. Pass the payment's DigetPay
transactionId (UUID) or its gateway paymentId:
final refund = await DigetPaySdk.refundS2s(
transactionId: payment.transactionId!,
amount: 0.11,
);
if (refund.isSuccess) {
print('${refund.result} · refundId=${refund.refundId} · ref=${refund.referenceId}');
}
Saved cards and tokenized charges
Charge a returning customer without asking for their card again:
- Save the card. Send a card sale with
saveToken: true. - Keep the token. Read
TKN-…from the result and store it on your server. - Charge it later. Call
tokenizationSale(). No card data and no hash are needed.
// 1–2. Save the card and read the token.
final sale = await DigetPaySdk.sale(SaleRequest(/* … */ saveToken: true));
final completion = await DigetPaySdk.completePayment(
context, sale, successUrl: successUrl, failureUrl: failureUrl,
);
final token = completion.details?.card?.token ?? sale.card?.token;
// 3. Charge it later.
final charge = await DigetPaySdk.tokenizationSale(
TokenizationSaleRequest(
orderId: 'ORD-1002',
amount: 20,
currency: 'SAR',
token: token!,
successUrl: successUrl,
),
);
print(charge.paymentDetails?.isApproved); // usually SUCCESS immediately
⚠️ A card token is a reusable payment credential. Store it server-side, never log it, and never show it in the UI.
Apple Pay
applePay() charges an Apple Pay token taken inside your own app.
Just want payers to have Apple Pay? Hosted checkout already offers it, with no Apple setup on your side.
What you need from Apple
Step by step: the Apple Pay guide walks through every step below with the example app: Merchant ID, DigetPay's certificate, Xcode, a first real payment, and TestFlight.
Apple encrypts every Apple Pay token for one merchant's certificate. Before
applePay() can charge, set up:
- An Apple Developer Program membership (paid).
- A Merchant ID. In Certificates, Identifiers & Profiles → Identifiers →
Merchant IDs, create one such as
merchant.com.yourcompany.app. - A Payment Processing Certificate for that Merchant ID:
- Request a CSR from DigetPay.
- Upload it to Apple to create the certificate.
- Send the resulting
.cerback to DigetPay, so it can decrypt your tokens.
- The Apple Pay capability. In Xcode, open Runner → Signing &
Capabilities, add Apple Pay, and tick your Merchant ID. This adds the
com.apple.developer.in-app-paymentsentitlement. - A real iPhone for testing. Sign in with an Apple sandbox tester account that has one of Apple's test cards in Wallet. Simulator tokens can't be decrypted.
Apple's App Review rules require an official Apple Pay button design.
Step 1: get the token from Apple's payment sheet
The SDK accepts a token from any PassKit integration. For example, add the
pay package to your app:
import 'package:pay/pay.dart';
const applePayConfig = '''{
"provider": "apple_pay",
"data": {
"merchantIdentifier": "merchant.com.yourcompany.app",
"displayName": "Your Store",
"merchantCapabilities": ["3DS", "debit", "credit"],
"supportedNetworks": ["mada", "visa", "masterCard"],
"countryCode": "SA",
"currencyCode": "SAR"
}
}''';
ApplePayButton(
paymentConfiguration: PaymentConfiguration.fromJsonString(applePayConfig),
paymentItems: const [
PaymentItem(label: 'Total', amount: '1.00', status: PaymentItemStatus.final_price),
],
type: ApplePayButtonType.buy,
onPaymentResult: (result) =>
payWithDigetPay(context, ApplePayToken.fromPayResult(result)),
loadingIndicator: const CircularProgressIndicator(),
);
Check that your
payversion lists mada among its supported networks. mada cards are essential for payers in Saudi Arabia.
ApplePayToken.fromPayResult(result) reads the pay result. If your own
native code already has the token as JSON, use ApplePayToken.fromMap({...})
instead.
Step 2: charge it with applePay()
Future<void> payWithDigetPay(BuildContext context, ApplePayToken token) async {
const successUrl = 'https://example.com/success';
const failureUrl = 'https://example.com/failure';
final response = await DigetPaySdk.applePay(
ApplePaySaleRequest(
orderId: 'ORDER-APPLE-001',
amount: 1, // must equal the amount on the Apple Pay sheet
currency: 'SAR',
token: token,
customer: const Customer(
name: 'Test Customer',
email: 'customer@example.com',
phone: '966512345678',
),
successUrl: successUrl,
failureUrl: failureUrl,
),
);
if (!context.mounted) return;
final completion = await DigetPaySdk.completePayment(
context, response, successUrl: successUrl, failureUrl: failureUrl,
);
print(completion.outcome); // approved / declined / pending
}
The SDK builds the request body and its integrity hash for you (abridged):
{
"orderId": "ORDER-APPLE-001",
"amount": 1,
"currency": "SAR",
"paymentMethod": "applepay",
"auth": "N",
"applePayToken": {
"paymentData": {
"version": "EC_v1",
"data": "…",
"signature": "…",
"header": { "ephemeralPublicKey": "…", "publicKeyHash": "…", "transactionId": "…" }
},
"transactionIdentifier": "…"
},
"customer": { "name": "…", "email": "…", "phone": "…" },
"successUrl": "…",
"failureUrl": "…",
"hash": "…"
}
Set auth: true on the request for an authorization-only hold. The token is
never logged. Treat it as sensitive and never store it.
Tamara (pay later)
tamaraSale() starts a Tamara buy now, pay later payment. No card data is
involved, and the integrity hash is computed for you. The response carries a
link to Tamara's page, which completePayment() opens:
const successUrl = 'https://example.com/success';
const failureUrl = 'https://example.com/failure';
final response = await DigetPaySdk.tamaraSale(
TamaraSaleRequest(
orderId: orderId,
amount: 125.52,
currency: 'SAR',
customer: const Customer(
name: 'Demo User',
email: 'demo@example.com',
phone: '+966500000000',
),
successUrl: successUrl,
failureUrl: failureUrl,
),
);
final completion = await DigetPaySdk.completePayment(
context, response, successUrl: successUrl, failureUrl: failureUrl,
);
Payment status
Two lookups return the same typed PaymentDetails record:
// Any S2S payment — by DigetPay transactionId (UUID) or gateway paymentId:
final payment = await DigetPaySdk.getPaymentStatus(id);
// GET /v1/payment/s2s/transaction/{transactionId}
// The payment made through a hosted-checkout session:
final sessionPayment = await DigetPaySdk.getCheckoutSessionTransaction(sessionId);
// GET /v1/payment/checkout/{sessionId}/transaction
if (payment?.isApproved ?? false) {
// status == SUCCESS
}
PaymentDetails |
Contains |
|---|---|
status · isApproved |
SUCCESS, PENDING, FAILED, … |
transactionId · paymentId · orderId |
Identifiers |
amount · currency · amountDetails |
Amount, plus the fee and currency breakdown |
paymentFlow · transactionType |
e.g. DIRECT_S2S, TOKENIZATION / PURCHASE |
card |
Masked number, brand, issuer, saved token |
transaction |
Gateway record: reference, authorization code, response code, ECI |
customer · invoice · suppliers · event |
Payer, invoice, settlement shares, last webhook event |
Both lookups return null on 404, a network error, or an error response.
Responses and errors
Every payment call returns a DigetPayResponse. HTTP errors and declines come
back as an unsuccessful response; they never throw:
DigetPayResponse |
Meaning |
|---|---|
isSuccess |
2xx and not declined/failed |
status · result · action |
e.g. PENDING · REDIRECT · SALE / AUTH |
transactionId · paymentId · orderId |
Identifiers |
html · redirectUrl · needsRedirect |
A 3-D Secure / redirect step, handled by completePayment() |
card · cardBrand |
Card summary, including card.token when saveToken was set |
refundId · referenceId |
Refund identifiers |
paymentDetails |
The typed PaymentDetails record, when the body carries one |
message · errorCode · declineReason |
Failure detail |
data |
The raw decoded payload |
Sensitive data
The SDK hands you everything the backend returns, but never logs it:
PaymentCard.numberis already masked (512345xxxxxx0008) and safe to show.PaymentCard.nameOnCardand the customer fields are PII. Display them, but don't log or store them broadly.PaymentCard.tokenandApplePayTokenare payment credentials. Keep tokens server-side, never log them, and never show them in the UI.
Debug logging
Pass an optional logger to initialize() for a redacted step-by-step
trace. It shows the HTTP method, path and status, checkout milestones, and
the final result. It never receives the API key, card data, tokens, or
request/response bodies.
import 'dart:developer' as developer;
DigetPaySdk.initialize(
apiKey: '<key>',
logger: (message) => developer.log(message, name: 'DigetPay'),
);
checkout: creating session for order 6f… (1.0 SAR)
→ POST /payment/checkout/intiate
← 201 OK POST /payment/checkout/intiate {code=201, session=ab02…, redirect=https://fin-admin.digetpay.com/pay/checkout}
checkout: session ab02… created → opening WebView
webview → https://fin-admin.digetpay.com/pay/checkout/success
→ GET /payment/checkout/ab02…/transaction
← 200 OK GET /payment/checkout/ab02…/transaction {code=200, status=SUCCESS, txn=683c…}
checkout: APPROVED (status=SUCCESS) → onTransactionSuccess
Leave logger unset (the default) for no logging in production.
Example app
The example/ app is a runnable guide with one screen per
service. Each tile shows the DigetPaySdk method it calls and the endpoint
behind it:
| Checkout | Server-to-server (S2S) |
|---|---|
| Hosted Checkout · Checkout Session Transaction | Card Sale · Card Authorization · Refund · Tokenization Sale · Payment Status · Apple Pay Sale · Tamara Sale |
cd example
flutter run --dart-define=DIGETPAY_API_KEY=<your-production-key>
- ⚠️ It runs against the production API, so payments are real. Use small amounts (every screen offers 1 SAR and 0.11 SAR), and refund your test payments.
- Screens fill each other in. After a payment, its transaction id, saved card token, and checkout session id are pre-filled on the follow-up screens (Refund, Payment Status, Tokenization Sale, Checkout Session Transaction).
- Apple Pay needs your own Apple setup and a real iPhone. The Apple Pay
screen shows Apple's button and charges the token with
applePay(). Put your Merchant ID, bundle ID, and Team ID in two git-ignored local files, then run with--dart-define-from-file=apple_pay.local.json. The Apple Pay guide walks through it: Merchant ID, DigetPay certificate, Xcode, and a TestFlight build.
Platform setup
The plugin needs no native code, only standard network and WebView configuration.
Android
-
minSdkVersion24 (Android 7.0) inandroid/app/build.gradle. -
INTERNET permission in
android/app/src/main/AndroidManifest.xml. The release manifest doesn't include it automatically:<uses-permission android:name="android.permission.INTERNET"/>
iOS
- Deployment target iOS 13.0+ in
ios/Podfileand on the Runner target. - DigetPay is served over HTTPS, so the default App Transport Security
policy works unchanged. Avoid a blanket
NSAllowsArbitraryLoadsin production. - For
applePay()only, add the Apple Pay capability as described in that section.
Flutter web and desktop are not supported in this version.
Security
- Use a restricted mobile key.
apiKeyis embedded in your app binary, and anything shipped in a mobile app can be extracted. Initialize with a publishable / restricted mobile key scoped to client operations, never a full server secret. - Rotate exposed keys immediately, and keep privileged operations behind your own server.
- Prefer hosted checkout for card entry. Raw card data never touches your
app.
sale()andauthorize()are explicit opt-ins that carry the card number and CVV through your app, which widens your PCI-DSS scope.
Upgrading from 0.5
0.6.0 renames a few methods to match the services above. The old names still work but are deprecated:
| Before | Now |
|---|---|
cardPay() · CardPay |
checkout() · HostedCheckout |
externalPayment(ExternalPaymentRequest) |
tamaraSale(TamaraSaleRequest) |
SaleRequest.recurringInit |
SaleRequest.saveToken |
recurringS2s() |
tokenizationSale() |
applePay() now takes an ApplePaySaleRequest. See the
CHANGELOG for details.
MIT © DigetPay · Issues & source: https://github.com/DigetPay/digetpay_plugin
Libraries
- digetpay_plugin
- DigetPay — pure-Dart Flutter payment plugin.