payengine 3.0.0-alpha.1
payengine: ^3.0.0-alpha.1 copied to clipboard
The PayEngine Flutter SDK allows you to build delightful payment experiences in your native Android and iOS apps using Flutter
PayEngine SDK for Flutter #
The PayEngine Flutter SDK allows you to build delightful payment experiences in your native Android and iOS apps using Flutter. We provide powerful and customizable UI screens and elements that can be used out-of-the-box to collect your users' payment details
Installation #
Add PayEngine registry to your project:
allprojects {
repositories {
...your repositories
maven {
name = "pe-maven"
url = uri("https://maven.payengine.co/payengine")
credentials {
username = "<username>"
password = "<password>"
}
}
}
}
Contact PayEngine support for username and password
Prerequisites #
Android
To use secure fields components, you need to install and configure the Material Components theme in your app.
- Add the following dependency to your
app/build.gradlefile with the specified version:
implementation 'com.google.android.material:material:<version>'
- Set the appropriate style in your
styles.xmlfile:
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- ... -->
</style>
iOS
cd ios && pod install --repo-update && cd ..
Usage #
PayEngine config
final PayEngineConfig config = const PayEngineConfig(
publicKey: "pk_test_xxx",
scriptURL: "https://console.payengine.dev");
final String merchantId = "<your-merchant-id>";
Wrap the config in a Provider
PayEngineProvider(
config: Config.config,
child: const MyApp()
)
Merchant session
Register an access token callback once at startup. The native forms, the Pay
buttons, the fraud monitor session and the PayEngine web-component widget
all call it to get a merchant session token (scope default) and send it as
Session <token>. Your backend creates the session with PayEngine's
POST /api/merchant/{merchantId}/sessions (scope default) and your secret
key; the app asks your backend for it (below, POST {backend}/accessToken/{merchantId}).
Never ship the secret key in the app.
class MyAccessToken extends PEAccessToken with PEAccessTokenJson {
@override
final String accessToken;
@override
final int expiresIn;
MyAccessToken({required this.accessToken, required this.expiresIn});
}
PayEngineNative.setFetchAccessTokenCallback(() async {
final response = await http.post(
Uri.parse('$backendURL/accessToken/$merchantId'));
final json = jsonDecode(response.body);
return MyAccessToken(
accessToken: json['access_token'], expiresIn: json['expires_in']);
});
The callback is required. The callback may be called on a background thread; it must not block waiting on the main thread. The native SDK waits for the Dart callback for up to 10 seconds.
Without it, or when it throws, times out, or returns a blank token or an
expiresIn of 5 seconds or less, no request is sent. The call that needed the
token fails with:
PlatformException(
code: 'MISSING_ACCESS_TOKEN', // PayEngineNative.missingAccessTokenCode
message: PayEngineNative.missingAccessTokenMessage,
details: {'reason': 'noCallback' | 'callbackFailed' | 'emptyToken', 'cause': ...},
)
That covers tokenize() on the forms, userCanPay, the Pay buttons'
onPaymentFailed and getFraudMonitorSession. The PayEngine widget doesn't
load and sends {'type': 'error', 'detail': {'code': 'MISSING_ACCESS_TOKEN', 'message': ..., 'reason': ...}} to its onEvent. The public key in
PayEngineConfig only selects the environment and loads the web SDK script;
it doesn't authenticate requests.
Credit Card Form
var additionalFields = List<PayEngineField>.from([
PayEngineField('address_zip', 'text', 'Zip Code', true,
keyboardType: PayEngineKeyboardType.number,
pattern:
r"^(?:\d{5}(?:-\d{4})?|[ABCEGHJKLMNPRSTVXY]\d[A-Z] ?\d[A-Z]\d)$"),
]);
final creditCardForm = CreditCardForm(additionalFields: additionalFields);
Container(padding: const EdgeInsets.all(10), child: creditCardForm),
OutlinedButton(
onPressed: () async {
final additionalData = <String, String>{
"address_street": "123 My Street"
};
final response = await creditCardForm.tokenize(
merchantId, // optional,
additionalData // optional
);
setState(() {
result = response;
});
},
child: const Text('Tokenize')),
Bank Account Form
final bankAccountForm = BankAccountForm();
Container(padding: const EdgeInsets.all(10), child: bankAccountForm),
OutlinedButton(
onPressed: () async {
final additionalData = <String, String>{};
final response = await bankAccountForm.tokenize(
merchantId, // optional,
additionalData // optional
);
setState(() {
result = response;
});
},
child: const Text('Tokenize')),
Google Pay and Apple Pay #
Check whether is supported or not:
final isSupported = PayEngineNative.userCanPay(PayProvider.applePay, Config.merchantId)
Always call this method before rendering the pay button, see the example below.
Google Pay
final paymentRequest = PEPaymentRequest(
merchantId: Config.merchantId,
paymentAmount: 10.00,
paymentItems: [
PEPaymentItem(
label: "Test Item",
amount: 10.00,
)
],
platformOptions: PEGooglePayOptions(billingAddressRequired: true, shippingAddressRequired: true)
);
// render button
FutureBuilder<bool>(
future: PayEngineNative.userCanPay(
PayProvider.googlePay, Config.merchantId),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(
child: Text(
'${snapshot.error}',
),
);
} else if (snapshot.data == true) {
return PEGooglePayButton(
paymentRequest: paymentRequest,
onPaymentFailed: (error) {
debugPrint("onPaymentFailed $error");
result = error.toString();
},
onPaymentSheetDismissed: () {
debugPrint("onPaymentSheetDismissed");
},
onTokenDidReturn: (token, metadata, billingAddress, shippingAddress) {
debugPrint("onTokenDidReturn $token $metadata ${billingAddress?.toJson()} ${shippingAddress?.toJson()}");
result = token;
},
);
} else {
return const Text("Google Pay is not supported");
}
} else {
return const SizedBox.shrink();
}
})
Apple Pay
final paymentRequest = PEPaymentRequest(
merchantId: Config.merchantId,
paymentAmount: 10.00,
paymentItems: [
PEPaymentItem(
label: "Test Item",
amount: 10.00,
)
],
platformOptions: PEApplePayOptions(
requiredBillingContactFields: [PEContactField.postalAddress],
requiredShippingContactFields: [PEContactField.name])
);
// render button
FutureBuilder<bool>(
future: PayEngineNative.userCanPay(
PayProvider.applePay, Config.merchantId),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(
child: Text(
'${snapshot.error}',
),
);
} else if (snapshot.data == true) {
return PEApplePayButton(
paymentRequest: paymentRequest,
onPaymentFailed: (error) {
debugPrint("onPaymentFailed $error");
result = error.toString();
},
onPaymentSheetDismissed: () {
debugPrint("onPaymentSheetDismissed");
},
onTokenDidReturn: (token, metadata, billingContact, shippingContact) {
debugPrint("onTokenDidReturn $token $metadata ${billingContact?.toJson()} ${shippingContact?.toJson()}");
result = token;
},
);
} else {
return const Text("Apple Pay is not supported");
}
} else {
return const SizedBox.shrink();
}
})
Example app #
The app in example/ runs against Sandbox, Staging, Production or a local
stack and gets merchant sessions from the test-sample-app backend; it holds
no secret key. make sample-config creates example/env.json, then
make sample-run-sandbox (or -staging, -production, -local) runs it.
See example/README.md; make help lists the targets.