v0.0.5uni_payments
Uni Payments integriert verschiedene Zahlungsgateways für schnelle und einfache Transaktionen.
NehilKoshiya/uni_payments open-source repository details.
{"sdk":"flutter"}^1.4.5^1.0.6^1.1.0^1.0.4^3.3.0^7.0.1^14.0.0^2.4.0+52^3.0.2^1.4.5^1.7.14^0.4.0{"sdk":"flutter"}^6.0.0Englischer Projektschnappschuss. Aktuelle Inhalte auf GitHub.
Thirteen payment gateways. One Future<PaymentResult>. Zero glue code.
A unified Flutter API over Razorpay · Stripe · PayPal · Paystack · Flutterwave · Paytm · Cashfree · PhonePe · PayU · Square · Airwallex · Google Pay · Apple Pay.
pub pub points flutter dart license
Razorpay Stripe PayPal Paystack Flutterwave Paytm Cashfree PhonePe PayU Square Airwallex Google Pay Apple Pay
final result = await UniPayments.payWithRazorpay(
keyId: 'YOUR_RAZORPAY_KEY_ID',
amount: 25.00,
businessName: 'Acme Inc',
customer: UniCustomer(name: 'Ada', email: 'ada@x.com', phone: '9999999999'),
);
switch (result) {
case PaymentSuccess(:final transactionId): /* verify on backend */
case PaymentFailure(:final errorCode, :final message): /* show error */
case PaymentCancelled(): /* user dismissed the sheet */
}
Swap
payWithRazorpayforpayWithStripe,payWithPaypal,payWithGooglePay, … every gateway still returns the samePaymentResult, while some hosted/native sheets also need aBuildContext.
Why this exists · Gateways · Install · Core types · Cookbook · Demo app · Security
Thirteen gateway SDKs ship thirteen call shapes, thirteen response objects, thirteen ways the user can cancel. Even when you wrap them, "user closed the sheet" usually disappears into a generic catch.
Uni Payments replaces all of that with a single sealed result type that the Dart compiler forces you to exhaust — every switch you write is checked at compile time, so you can't forget the cancel case again.
| Before | With Uni Payments | |
|---|---|---|
| API per gateway | Different class, different callbacks, different error shape | UniPayments.payWith*(...) everywhere |
| Cancellation | Hidden inside catch (e) or a stringy status |
PaymentCancelled — a real type |
| Verification | Dig through gateway-specific JSON | result.transactionId + result.rawResponse |
| Native setup | 13 different setup guides | Documented per gateway here |
| Gateway | Region | SDK | Imperative call | Native button |
|---|---|---|---|---|
| Razorpay | India | razorpay_flutter |
payWithRazorpay |
— |
| Stripe | Global | flutter_stripe |
payWithStripe |
— |
| PayPal | Global | braintree_flutter_plus |
payWithPaypal |
— |
| Paystack | Africa | flutter_paystack_max |
payWithPaystack |
— |
| Flutterwave | Africa | flutterwave_standard |
payWithFlutterwave |
— |
| Paytm | India | paytmpayments_allinonesdk |
payWithPaytm |
— |
| Cashfree | India | flutter_cashfree_pg_sdk |
payWithCashfree |
— |
| PhonePe | India · UPI | phonepe_payment_sdk |
payWithPhonepe |
— |
| PayU | India · LatAm · Turkey · CEE | payu_checkoutpro_flutter |
payWithPayu |
— |
| Square | US · UK · CA · AU | square_in_app_payments |
payWithSquare |
— |
| Airwallex | Global · APAC-strong | airwallex_payment_flutter |
payWithAirwallex |
— |
| Google Pay | Android | pay |
payWithGooglePay |
googlePayButton(...) |
| Apple Pay | iOS | pay |
payWithApplePay |
applePayButton(...) |
Every imperative call returns Future<PaymentResult>. Wallet buttons exist because Google + Apple's brand guidelines require their own button design.
dependencies:
uni_payments: ^0.0.9
flutter pub add uni_payments
import 'package:uni_payments/uni_payments.dart';
| Platform | Minimum |
|---|---|
| Flutter | 3.41+ · Dart 3.8+ (required for flutter_stripe 14.x) |
| Android | minSdkVersion 23 — modern Stripe / Razorpay / PhonePe builds need it. 28+ if you use Square. |
| iOS | iOS 16+ — required by braintree_flutter_plus 7.x and compatible with the other SDKs |
Square's In-App Payments SDK requires minSdkVersion 28 (Android 9). minSdkVersion is a single app-wide setting, so if you use payWithSquare, raise it in your app's android/app/build.gradle.kts:
android {
defaultConfig {
minSdk = 28
}
}
Skip this if you're not using Square — every other gateway in this package works down to minSdkVersion 23.
PhonePe's IntentSDK is hosted on PhonePe's CloudRepo, not on Maven Central. Add the repository to your app's android/build.gradle.kts:
allprojects {
repositories {
google()
mavenCentral()
maven { url = uri("https://phonepe.mycloudrepo.io/public/repositories/phonepe-intentsdk-android") }
}
}
Groovy DSL equivalent in android/build.gradle:
maven { url 'https://phonepe.mycloudrepo.io/public/repositories/phonepe-intentsdk-android' }
UniCustomerPass once, reuse everywhere a gateway prefills checkout fields.
const customer = UniCustomer(
name: 'Ada Lovelace',
email: 'ada@example.com',
phone: '9999999999', // optional
);
PaymentResultsealed class PaymentResult {
String? gatewayName; // 'razorpay', 'stripe', 'apple_pay', …
String? message;
Map<String, dynamic>? rawResponse;
}
final class PaymentSuccess extends PaymentResult { String transactionId; }
final class PaymentFailure extends PaymentResult { String errorCode; String message; }
final class PaymentCancelled extends PaymentResult { }
rawResponse holds the untouched gateway payload — useful for audit logs and webhook reconciliation.
UniPayments.isWalletSupportedProbe before rendering a wallet button — the underlying pay package silently no-ops on unsupported platforms.
final canApplePay = await UniPayments.isWalletSupported(
WalletProvider.applePay,
configJson,
);
final result = await UniPayments.payWithRazorpay(
keyId: 'YOUR_RAZORPAY_KEY_ID',
amount: 25.00, // major units (₹25.00)
businessName: 'Acme Inc', // merchant header inside the sheet
customer: customer,
description: 'Pro subscription',
themeColor: Colors.indigo, // Color, not '#RRGGBB'
currency: 'INR',
timeout: const Duration(minutes: 5), // optional — see below
);
By default this waits indefinitely for the checkout to complete. Pass
timeoutto get aPaymentFailureinstead of hanging forever if the SDK never calls back (e.g. the app was backgrounded and killed).
final result = await UniPayments.payWithStripe(
publishableKey: 'YOUR_STRIPE_PUBLISHABLE_KEY',
clientSecret: 'YOUR_PAYMENT_INTENT_CLIENT_SECRET', // from your server
merchantDisplayName: 'Acme Inc',
merchantCountryCode: 'US',
// Optional — Apple Pay / Google Pay inside the PaymentSheet
applePayMerchantId: 'merchant.com.acme.app',
googlePayTestEnv: true,
// Optional — saved cards (ephemeral key from your server)
customerId: 'cus_xxx',
customerEphemeralKeySecret: 'ek_test_xxx',
);
final result = await UniPayments.payWithPaypal(
context: context,
tokenizationKey: 'YOUR_BRAINTREE_TOKENIZATION_KEY',
amount: 25.00,
customer: customer,
currency: 'USD',
countryCode: 'US',
applePayMerchantId: 'merchant.com.acme', // optional
);
final result = await UniPayments.payWithPaystack(
context: context,
secretKey: 'YOUR_PAYSTACK_SECRET_KEY',
amount: 25.00,
customer: customer,
reference: 'ref_${DateTime.now().millisecondsSinceEpoch}',
callbackUrl: 'https://acme.dev/paystack/callback',
currency: UniPaystackCurrency.usd,
);
final result = await UniPayments.payWithFlutterwave(
context: context,
publicKey: 'YOUR_FLUTTERWAVE_PUBLIC_KEY',
currency: 'NGN',
amount: 25.00,
customer: customer,
txRef: 'tx_${DateTime.now().millisecondsSinceEpoch}',
redirectUrl: 'https://acme.dev/flutterwave/return',
testMode: true,
);
Standard checkout only needs your public key. Encryption happens on Flutterwave's hosted modal.
// txnToken is issued by your backend via Paytm's initiateTransaction API.
final result = await UniPayments.payWithPaytm(
merchantId: 'YOUR_MERCHANT_ID',
orderId: 'order_${DateTime.now().millisecondsSinceEpoch}',
txnToken: 'YOUR_TXN_TOKEN',
amount: 25.00,
useStagingEnvironment: true,
);
// orderId + paymentSessionId come from your backend's call to the
// Cashfree Orders API.
final result = await UniPayments.payWithCashfree(
orderId: 'order_${DateTime.now().millisecondsSinceEpoch}',
paymentSessionId: 'session_xxx',
useStagingEnvironment: true,
timeout: const Duration(minutes: 5), // optional, see below
);
Only one Cashfree payment can be in flight at a time — the upstream SDK is a process-wide singleton. Calling this again before a prior call resolves fails fast with
PaymentFailure(errorCode: 'cashfree_already_in_progress')instead of corrupting the first call.timeoutworks the same way as Razorpay's above.
// requestBody is a base64-encoded JSON request your backend signs.
final result = await UniPayments.payWithPhonepe(
merchantId: 'YOUR_MERCHANT_ID',
flowId: 'flow_${DateTime.now().millisecondsSinceEpoch}',
requestBody: '<base64-encoded JSON from your backend>',
appSchema: 'unipaymentsdemo', // iOS URL scheme; '' on Android
useStagingEnvironment: true,
);
Also requires the Maven repo described in Required extra setup.
// Backend hands you a hash for every step PayU asks you to sign — see
// https://devguide.payu.in/flutter-sdk-integration/. Never compute this
// with the salt on-device.
Future<Map<dynamic, dynamic>> generateHash(Map<dynamic, dynamic> request) async {
final response = await yourBackend.post('/payu/hash', body: request);
return response.data; // e.g. { hashName: 'computedHashValue' }
}
final result = await UniPayments.payWithPayu(
merchantKey: 'YOUR_PAYU_MERCHANT_KEY',
amount: 25.00,
productInfo: 'Pro subscription',
customer: customer,
transactionId: 'txn_${DateTime.now().millisecondsSinceEpoch}',
successUrl: 'https://acme.dev/payu/success',
failureUrl: 'https://acme.dev/payu/failure',
generateHash: generateHash,
useStagingEnvironment: true,
);
Advanced CheckoutPro options (SI/subscriptions, split payments, EMI, custom notes, …) go through the optional
additionalPaymentParams/checkoutConfigmaps, using PayU's raw keys frompayu_checkoutpro_flutter'sPayUConstantKeys.
final result = await UniPayments.payWithSquare(
applicationId: 'YOUR_SQUARE_APPLICATION_ID', // sandbox-sq0idb-... or sq0idp-...
);
This only tokenizes a card into a one-time-use nonce — Square's mobile SDK doesn't charge cards itself. Send
result.transactionId(the nonce) to your backend and charge it via Square's Payments API. Sandbox vs. production is decided entirely by whichapplicationIdyou pass. Also requiresminSdkVersion 28on Android — see Required extra setup.
final result = await UniPayments.payWithAirwallex(
clientSecret: 'YOUR_PAYMENT_INTENT_CLIENT_SECRET', // from your server
paymentIntentId: 'YOUR_PAYMENT_INTENT_ID',
amount: 25.00,
currency: 'USD',
countryCode: 'US',
useStagingEnvironment: true,
);
Presents Airwallex's full hosted payment sheet (cards, wallets, and local redirect methods, depending on what your account supports). A result of
errorCode: 'payment_in_progress'means the payment was submitted but its outcome isn't confirmed yet — the same situation as Razorpay's external-wallet case — verify via your backend before fulfilling.
// Imperative
final result = await UniPayments.payWithGooglePay(
paymentConfigurationJson: configJson,
lineItemLabel: 'Total',
amount: 25.00,
);
// Native button
UniPayments.googlePayButton(
paymentConfigurationJson: configJson,
lineItemLabel: 'Total',
amount: 25.00,
buttonType: UniGooglePayButtonType.pay,
onResult: (PaymentResult result) { /* … */ },
);
final result = await UniPayments.payWithApplePay(
paymentConfigurationJson: configJson,
lineItemLabel: 'Total',
amount: 25.00,
);
UniPayments.applePayButton(
paymentConfigurationJson: configJson,
lineItemLabel: 'Total',
amount: 25.00,
type: UniApplePayButtonType.buy,
onResult: (PaymentResult result) { /* … */ },
);
The repo ships a fully-styled demo with all thirteen gateways wired up — animated gradient background, glass-morphism tiles, error toasts, haptic feedback on each outcome.
git clone https://github.com/NehilKoshiya/uni_payments
cd uni_payments/example
flutter pub get
flutter run
Secrets
secretKey (Paystack), the PayU merchant salt, and Stripe/Airwallex clientSecrets must be generated or held on your server — a decompiled APK/IPA hands over anything embedded in it.payWithPayu's generateHash callback exists specifically so the salt stays server-side; don't be tempted to inline the hash logic on-device "just for testing."Verification
PaymentSuccess — re-check with the gateway (fetch the payment/order by id, or wait for its webhook) before shipping anything.PaymentFailure / PaymentCancelled — don't assume no money moved. Bank debits and UPI/wallet redirects can complete after the client already gave up; several gateways in this package surface that explicitly as a specific errorCode (e.g. external_wallet_pending from Razorpay, payment_in_progress from Airwallex, cashfree_already_in_progress) precisely so you don't silently treat "ambiguous" as "definitely unpaid."orderId/signature in rawResponse, Paytm's checksum, PayU's hash), verify that signature server-side too — rawResponse carries the untouched payload specifically so your backend has something to check against, not just log.Reliability
reference / transactionRef / orderId / transactionId per attempt (not reused across retries) — every gateway that takes one uses it to detect duplicate charges on their end.payWithRazorpay and payWithCashfree accept an optional timeout — without one, a native SDK that never calls back (killed app, OEM quirk) leaves the Future pending forever with no way for your UI to recover.Dependencies
flutter_stripe and the other native SDKs current — dart pub outdated should show no available upgrades left on the table; payment SDKs receive security-relevant patches (fraud signals, TLS/crypto updates) more often than most packages.git clone https://github.com/NehilKoshiya/uni_payments
cd uni_payments
flutter pub get
flutter test
cd example && flutter pub get
flutter analyze must be clean. This package runs with strict-casts, strict-inference and strict-raw-types on top of flutter_lints (see analysis_options.yaml) — code that's merely "lint-clean" elsewhere may still fail here.flutter test must pass.cd example && flutter run) and exercise the affected gateway's tile before opening the PR — analysis and tests don't catch a broken demo wiring.Every gateway in this package follows the same shape, so a new one is mostly mechanical:
lib/src/gateways/<name>_gateway.dart — a stateless <Name>Gateway class with a pay(...) method that awaits/wraps the upstream SDK and maps its outcome onto PaymentSuccess / PaymentFailure / PaymentCancelled. Give it a const _gatewayName = '<name>'; matching the public method name, and stash the untouched upstream response in rawResponse wherever you can.lib/src/uni_payments.dart — add a payWithXxx(...) static method that validates required fields via _validate(...) and delegates to the new gateway. Document any upstream quirks in the doc comment (see payWithCashfree for an example of calling out an upstream concurrency limitation).pubspec.yaml — add the dependency, and check its environment: constraint before pinning — don't silently raise this package's Flutter/Dart floor for an optional gateway (see the square_in_app_payments comment for the pattern).example/ — add a tile (lib/data/gateway.dart), a demo method (lib/services/payment_demos.dart), wire it into the dispatch map (lib/ui/home_screen.dart), and add a brand color/letter fallback (lib/ui/brand_icon.dart) if Simple Icons doesn't have the logo.README.md — add a row to the Gateways table and a cookbook entry under Per-gateway cookbook.CHANGELOG.md — new gateways get their own entry under "New gateways."Before proposing a gateway, do the same vetting this package already applies: check pub.dev for maintenance status (points, likes, last published date, and whether it's marked discontinued), and skim the native bridge source for obvious gaps (does every outcome — including cancellation — actually reach Dart?). Two candidates were rejected for exactly these reasons; see the CHANGELOG.
MIT · © Nehil Koshiya