Flutter SDK

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.

ItemDetails
Packagesadadpay_flutter
Source codegithub.com/Sadadkw/sadad-flutter-sdk
Latest version0.0.5
RequirementsDart 3.2 or later. Uses webview_flutter and dio.
PlatformsAndroid and iOS

How it works

1. App asks your server
"Start checkout for order 1001"
→
2. Server creates the invoice
SADAD Pay API, returns the payment URL
→
3. App shows SadadWebView
Customer pays inside the app
→
4. Server verifies
status = Paid, then confirm the order

❗️

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:

  1. Create the invoice with POST /api/Invoice/insert. It returns the invoiceId.
  2. Get the invoice with GET /api/Invoice/getbyid?id={invoiceId}. The url field is the payment page.
  3. Save the invoiceId with the order, and return the url to 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

ParameterTypeRequiredDescription
urlStringYesThe payment page URL, for example https://sandbox.sadadpay.net/pay/5527187292968
onSuccessFunctionYesCalled when the payment page reports a successful payment
onFailFunctionYesCalled when the payment page reports a failed payment
appBarAppBar?NoAn app bar shown above the payment page

🚧

Upgrading from older examples

Older examples pass invoiceKey to SadadWebView. In the current version the parameter is url. 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:

  1. The app calls your server, for example GET /api/orders/{orderId}.
  2. Your server calls GET /api/Invoice/getbyid?id={invoiceId} and checks that status is Paid and the amount matches. See Verify Payment Status.
  3. 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'];
MethodCallsReturns
generateRefreshToken(clientKey:, clientSecret:)POST /User/GenerateRefreshTokenThe JSON response. The token is in ['response']['refreshToken'].
generateAccessToken(refreshToken:)POST /User/GenerateAccessTokenThe JSON response. The token is in ['response']['accessToken'].
createInvoice(invoices:, token:)POST /Invoice/insertThe JSON response. The ID is in ['response']['invoiceId'].
getInvoice(invoiceId:, token:)GET /Invoice/getbyidThe JSON response, with status, key and url
EnvironmentAPI
Environment.dev (default)Sandbox, https://apisandbox.sadadpay.net/api
Environment.stageSandbox, https://apisandbox.sadadpay.net/api
Environment.prodLive, https://api.sadadpay.net/api

Things to know about these methods:

  • The token methods throw an error message when the request fails.
  • createInvoice and getInvoice return 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 CustomerNameRequired comes back with HTTP 200 and "isValid": false. Check isValid on every result.

What the SDK does not cover

The SDK covers the payment page only. For anything else, use your server and the API:

Troubleshooting

ProblemWhat to check
The named parameter 'invoiceKey' isn't definedYou are using an older example. Pass url: with the full payment URL.
The payment page stays on a loading spinnerThe URL is wrong or the device has no internet. On Android, check the INTERNET permission.
Neither callback runsThe 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 PaidAlways 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 LiveThe URL comes from your server. Check that it uses api.sadadpay.net and your Live keys.

Next steps