payengine 2.1.0-alpha.1
payengine: ^2.1.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
example/lib/main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:payengine/payengine.dart';
import 'package:payengine/payengine_provider.dart';
import 'package:payengine_example/config.dart';
import 'package:payengine_example/screens/credit_card_screen.dart';
import 'package:payengine_example/themes.dart';
void main() {
runApp(
PayEngineProvider(
config: Config.config,
child: const MyApp()
)
);
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
Map<dynamic, dynamic> result = {};
@override
void initState() {
super.initState();
// Set the fetch access token callback in the Flutter plugin
PayEngineNative.setFetchAccessTokenCallback(_fetchAccessToken);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: MyAppThemes.lightTheme,
darkTheme: MyAppThemes.darkTheme,
themeMode: ThemeMode.light,
home: const CreditCardScreen(),
);
}
}
// Function to fetch the access token
Future<PEAccessTokenJson> _fetchAccessToken() async {
final String baseUrl = Config.config.baseURL;
final String merchantId = Config.merchantId;
final String apiKey = Config.privateKey;
final Uri url = Uri.parse("$baseUrl/api/merchant/$merchantId/sessions");
final Map<String, dynamic> requestBody = {
"expires_in": 900, // Token valid for 15 minutes
};
final http.Response response;
try {
response = await http.post(
url,
headers: {
"Content-Type": "application/json",
"Authorization": "Basic $apiKey",
},
body: jsonEncode(requestBody),
);
} catch (e) {
throw Exception("Network request failed: $e");
}
if (response.statusCode != 200) {
throw Exception("HTTP Error: ${response.statusCode}");
}
final Map<String, dynamic> responseData = jsonDecode(response.body);
if (responseData["error"] == true) {
throw Exception("API Error: ${responseData["message"]}");
}
return AccessTokenImpl(
accessToken: responseData["access_token"],
expiresIn: responseData["expires_in"],
);
}
class AccessTokenImpl extends PEAccessToken with PEAccessTokenJson {
@override
final String accessToken;
@override
final int expiresIn;
AccessTokenImpl({required this.accessToken, required this.expiresIn});
}