Show the SADAD Pay payment page inside your Flutter app.
The SADAD Pay Flutter SDK shows the SADAD Pay payment page inside your app. The customer pays without leaving the app, and the SDK tells you when the payment page reports success or failure.
| Item | Details |
|---|---|
| Package | sadadpay_flutter |
| Source code | github.com/Sadadkw/sadad-flutter-sdk |
| Latest version | 0.0.5 |
| Requirements | Dart 3.2 or later. Uses webview_flutter and dio. |
| Platforms | Android and iOS |
How it works
Keep your Client Secret on your server
Never put your Client Key or Client Secret in your app. Anyone can extract them from an app download and use them to create invoices or refunds on your account. Create invoices on your own server, and send the app only the payment URL. The SDK also has methods that call the API directly from the app: use them only for quick tests in Sandbox. See API methods.
Step 1: Install
flutter pub add sadadpay_flutter
This adds the package to your pubspec.yaml:
dependencies:
sadadpay_flutter: ^0.0.5
The SDK shows the payment page with webview_flutter. Follow its platform setup if your app does not use web views yet. On Android, make sure your app has internet access in android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Step 2: Create the invoice on your server
Add an endpoint to your server that creates a SADAD Pay invoice for the order and returns its payment URL. This is the same as the Hosted Payment Page flow:
- Create the invoice with
POST /api/Invoice/insert. It returns theinvoiceId. - Get the invoice with
GET /api/Invoice/getbyid?id={invoiceId}. Theurlfield is the payment page. - Save the
invoiceIdwith the order, and return theurlto the app.
app.post('/api/checkout', async (req, res) => {
const order = await findOrder(req.body.orderId); // your own order lookup
const token = await getAccessToken(); // see API Keys & Authentication
const api = 'https://apisandbox.sadadpay.net/api'; // Live: https://api.sadadpay.net/api
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
// 1. Create the invoice
const created = await fetch(`${api}/Invoice/insert`, {
method: 'POST',
headers,
body: JSON.stringify({
Invoices: [{
ref_Number: order.number,
amount: order.total, // in KWD
customer_Name: order.customerName,
customer_Mobile: order.customerMobile,
lang: 'en',
currency_Code: 'KWD',
}],
}),
}).then(r => r.json());
if (!created.isValid) return res.status(400).json({ error: created.errorKey });
// 2. Get the payment URL
const invoiceId = created.response.invoiceId;
const invoice = await fetch(`${api}/Invoice/getbyid?id=${invoiceId}`, { headers }).then(r => r.json());
// 3. Save the invoice ID and return the URL
await saveInvoiceId(order, invoiceId);
res.json({ url: invoice.response.url });
});
See API Keys & Authentication for getAccessToken().
Step 3: Show the payment page in the app
Call your endpoint, then open SadadWebView with the URL it returns.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:sadadpay_flutter/widgets/web_view.dart';
Future<void> startCheckout(BuildContext context, String orderId) async {
final res = await http.post(
Uri.parse('https://yourserver.com/api/checkout'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'orderId': orderId}),
);
final url = jsonDecode(res.body)['url'] as String;
if (!context.mounted) return;
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => SadadWebView(
url: url,
appBar: AppBar(title: const Text('Payment')),
onSuccess: () {
Navigator.of(context).pop(); // close the payment page
checkOrder(context, orderId); // Step 4
},
onFail: () {
Navigator.of(context).pop();
showPaymentFailed(context);
},
),
));
}
This example uses the http package (flutter pub add http). Any HTTP client works.
SadadWebView parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
url | String | Yes | The payment page URL, for example https://sandbox.sadadpay.net/pay/5527187292968 |
onSuccess | Function | Yes | Called when the payment page reports a successful payment |
onFail | Function | Yes | Called when the payment page reports a failed payment |
appBar | AppBar? | No | An app bar shown above the payment page |
Upgrading from older examples
Older examples pass
invoiceKeytoSadadWebView. In the current version the parameter isurl. Pass the full payment URL instead, for example'https://sandbox.sadadpay.net/pay/$invoiceKey'(Live:'https://sadadpay.net/pay/$invoiceKey').
When the callbacks run
After payment, SADAD Pay sends the customer to a result page whose address ends in /Success or /Failed. SadadWebView watches for these addresses and, on the next page change, calls onSuccess or onFail and stops the web view from going further.
If the customer closes the payment page with the back button, neither callback runs. Check the order on your server in that case too.
Step 4: Verify the payment on your server
onSuccess tells you the payment page showed success. It is not proof of payment. Ask your server to check the invoice before you confirm the order:
- The app calls your server, for example
GET /api/orders/{orderId}. - Your server calls
GET /api/Invoice/getbyid?id={invoiceId}and checks thatstatusisPaidand the amount matches. See Verify Payment Status. - Your server returns the order status, and the app shows the result.
Also set up Webhooks, so your server learns about the payment even if the app is closed before it can check.
API methods (for testing only)
The SadadPay class can call the API straight from the app. Because this needs your Client Key and Client Secret in the app, use it only to try the SDK in Sandbox, never in an app you publish.
import 'package:sadadpay_flutter/config/env.dart';
import 'package:sadadpay_flutter/sadadpay.dart';
final sadadPay = SadadPay(env: Environment.dev); // Sandbox
final refresh = await sadadPay.generateRefreshToken(clientKey: 'SANDBOX_CLIENT_KEY', clientSecret: 'SANDBOX_CLIENT_SECRET');
final access = await sadadPay.generateAccessToken(refreshToken: refresh['response']['refreshToken']);
final token = access['response']['accessToken'];
final created = await sadadPay.createInvoice(token: token, invoices: {
'Invoices': [
{'ref_Number': 'TEST-1', 'amount': 1.000, 'customer_Name': 'Test', 'customer_Mobile': '99999999', 'lang': 'en', 'currency_Code': 'KWD'}
]
});
final invoice = await sadadPay.getInvoice(invoiceId: created['response']['invoiceId'].toString(), token: token);
final url = invoice['response']['url'];
| Method | Calls | Returns |
|---|---|---|
generateRefreshToken(clientKey:, clientSecret:) | POST /User/GenerateRefreshToken | The JSON response. The token is in ['response']['refreshToken']. |
generateAccessToken(refreshToken:) | POST /User/GenerateAccessToken | The JSON response. The token is in ['response']['accessToken']. |
createInvoice(invoices:, token:) | POST /Invoice/insert | The JSON response. The ID is in ['response']['invoiceId']. |
getInvoice(invoiceId:, token:) | GET /Invoice/getbyid | The JSON response, with status, key and url |
Environment | API |
|---|---|
Environment.dev (default) | Sandbox, https://apisandbox.sadadpay.net/api |
Environment.stage | Sandbox, https://apisandbox.sadadpay.net/api |
Environment.prod | Live, https://api.sadadpay.net/api |
Things to know about these methods:
- The token methods throw an error message when the request fails.
createInvoiceandgetInvoicereturn the error response instead of throwing when the API returns an HTTP error, so check the result before you read['response'].- A SADAD Pay error such as
CustomerNameRequiredcomes back with HTTP 200 and"isValid": false. CheckisValidon every result.
What the SDK does not cover
The SDK covers the payment page only. For anything else, use your server and the API:
- Embedded Payment with native KNET, card or Apple Pay buttons
- Refunds
- Payment links, Product Links, Subscriptions and Installments
Troubleshooting
| Problem | What to check |
|---|---|
The named parameter 'invoiceKey' isn't defined | You are using an older example. Pass url: with the full payment URL. |
| The payment page stays on a loading spinner | The URL is wrong or the device has no internet. On Android, check the INTERNET permission. |
| Neither callback runs | The customer left the payment page before the result page, or used the back button. Check the order status on your server. |
onSuccess runs but the invoice is not Paid | Always verify on your server before you confirm the order. Contact [email protected] with the invoice ID if this happens. |
| The page opens in Sandbox but you expected Live | The URL comes from your server. Check that it uses api.sadadpay.net and your Live keys. |
Next steps
- Follow the Go-Live Checklist before you publish your app.
- Using PHP on your server? See the PHP Library.

