setFetchAccessTokenCallback static method
Sets the callback PayEngine calls to get a merchant session access token.
The SDK sends the token as Authorization: Session <token> on every
request. This callback is required: PayEngine no longer accepts requests
signed with the public key.
Important
- Required: without it, or when it throws or returns a blank token
or an
expiresInof 5 seconds or less, no request is sent. The call that needed the token fails with a PlatformException with code missingAccessTokenCode (see there), and thePayEnginewidget doesn't load and sends anerrorevent to itsonEvent. - Global: there is one callback for the whole app. Calling this again replaces the previous callback and drops the token cached for it.
- Register it at startup, before any PayEngine view or widget is
shown. A
PayEnginewidget created before registration doesn't load. - Called whenever a token is needed: on the first request and again each time the current token expires or has to be refreshed. Return a fresh token on every call.
- Threading: the callback may be called on a background thread; it must not block waiting on the main thread. In Flutter the callback runs on the Dart isolate while the native SDK waits for it on a background thread for up to 10 seconds; after that the request fails with missingAccessTokenCode.
- Used by every PayEngine surface: the native credit card and bank
account forms, the Apple Pay / Google Pay buttons, the fraud monitor
session and the
PayEngineweb-component widget. The widget gets the token over its JavaScript channel, never through a URL or the page HTML. - Create the token on your backend with
POST /api/merchant/{merchantId}/sessions(scopedefault), using your secret key there. Never ship the secret key in the app.
See PayEngine Merchant Session.
Example
class MyAccessToken extends PEAccessToken with PEAccessTokenJson {
@override
final String accessToken;
@override
final int expiresIn;
MyAccessToken({required this.accessToken, required this.expiresIn});
}
void configurePayEngine() {
PayEngineNative.setFetchAccessTokenCallback(() async {
// Your backend calls POST /api/merchant/{merchantId}/sessions.
final session = await myBackend.createMerchantSession(merchantId);
return MyAccessToken(
accessToken: session.accessToken, expiresIn: session.expiresIn);
});
}
callback: returns the access token and its lifetime in seconds. Throw if the token can't be fetched. When a request gets a 401, the SDK calls it again for a new token and retries the request once.
Implementation
static void setFetchAccessTokenCallback(
Future<PEAccessTokenJson> Function() callback) {
_accessTokenProvider = callback;
// The native SDK asks Dart for tokens over this channel.
_channel.setMethodCallHandler(_fetchAccessTokenHandler);
_channel.invokeMethod('setFetchAccessTokenCallback', {});
}