ansa_flutter_sdk 0.0.4
ansa_flutter_sdk: ^0.0.4 copied to clipboard
Ansa Flutter SDK - A Flutter SDK for integrating Ansa Core and Ansa UI functionalities into your Flutter applications.
example/lib/main.dart
import 'package:ansa_flutter_sdk/ansa_logger.dart' show LogLevel;
import 'package:ansa_flutter_sdk/models/add_balance_request.dart';
import 'package:ansa_flutter_sdk/models/add_payment_method_type.dart';
import 'package:ansa_flutter_sdk/models/auto_reload_config.dart';
import 'package:ansa_flutter_sdk/models/auto_reload_configuration_request.dart';
import 'package:ansa_flutter_sdk/models/use_balance_request.dart';
import 'package:flutter/material.dart';
import 'package:ansa_flutter_sdk/models/merchant.dart';
import 'package:ansa_flutter_sdk/models/payment_method.dart';
import 'package:ansa_flutter_sdk/models/customer.dart';
import 'package:ansa_flutter_sdk/ansa_flutter_sdk.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Ansa Flutter SDK Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late AnsaFlutterSdk _ansaFlutterSdk;
String _result = '';
final String _publishableKey =
'ansa_pk_sandbox_huRltYRsD2hXD0yeMxA/7i88UJan4Ez+';
final String _customerId = '97fcbe81-61ac-4839-a209-e5cb164a8e92';
final String _merchantId = '3a8528eb-d0d5-46b6-9adb-62f669de55e5';
final String paymentMethodId = 'pm_1P73iXKVmG7QtMGnWlsw4Tng';
@override
void initState() {
super.initState();
_ansaFlutterSdk = AnsaFlutterSdk();
_setupClientSecretProvider();
}
void _setupClientSecretProvider() {
// Set up the client secret provider first
_ansaFlutterSdk.setupClientSecretProvider((customerId) async {
// Provide the client secret dynamically
return 'ansa_sk_sandbox_KSrB0dvHuCi9pMisMzvx2mvDwbwgXYYF';
});
// Once setup is complete, initialize the SDK
_initializeSdk();
}
Future<void> _initializeSdk() async {
try {
await _ansaFlutterSdk.initializeSdk(
publishableKey: _publishableKey,
logLevel: LogLevel.info,
);
} on Exception catch (e) {
setState(() {
_result = 'Failed to initialize SDK: ${e.toString()}';
});
}
}
Future<void> _fetchCustomer() async {
setState(() {
_result = 'Loading...';
});
try {
Customer customer =
await _ansaFlutterSdk.customer.getCustomer(customerId: _customerId);
setState(() {
_result = '''
Customer ID: ${customer.id}
Email: ${customer.email ?? 'N/A'}
Phone: ${customer.phone ?? 'N/A'}
Status: ${customer.status}
Balance: ${customer.balance.amount} ${customer.balance.currency}
Is Tap To Pay Enabled: ${customer.isTapToPayEnabled}
''';
});
} catch (e) {
setState(() {
_result = 'Failed to fetch customer data. Please try again.';
});
}
}
Future<void> _fetchPaymentMethods() async {
setState(() {
_result = 'Loading...';
});
try {
List<PaymentMethod> paymentMethods = await _ansaFlutterSdk.customer
.getPaymentMethods(customerId: _customerId);
setState(() {
_result = paymentMethods.map((pm) {
return '''
Payment Method ID: ${pm.id}
Type: ${pm.type}
Card Brand: ${pm.card.brand}
Fingerprint: ${pm.card.fingerprint}
First Six: ${pm.card.firstSix}
Last Four: ${pm.card.lastFour}
''';
}).join('\n');
});
} catch (e) {
setState(() {
_result = 'Failed to fetch payment methods. Please try again.';
});
}
}
Future<void> _fetchMerchant() async {
setState(() {
_result = 'Loading...';
});
try {
Merchant merchant =
await _ansaFlutterSdk.merchant.getMerchant(merchantId: _merchantId);
setState(() {
_result = '''
Merchant ID: ${merchant.id}
Name: ${merchant.name}
Is Tap To Pay Enabled: ${merchant.metadata?.isTapToPayEnabled ?? 'N/A'}
OMS Provider: ${merchant.metadata?.omsProvider ?? 'N/A'}
Payment Processor: ${merchant.metadata?.paymentProcessor ?? 'N/A'}
''';
});
} catch (e) {
setState(() {
_result = 'Failed to fetch merchant data. Please try again.';
});
}
}
Future<void> _fetchCardArtUrls() async {
setState(() {
_result = 'Loading...';
});
try {
List<String> cardArtUrls =
await _ansaFlutterSdk.merchant.getCardArtUrls();
setState(() {
_result = cardArtUrls.join(', ');
});
} catch (e) {
setState(() {
_result = 'Failed to fetch card art. Please try again.';
});
}
}
Future<void> _addPaymentMethod() async {
setState(() {
_result = 'Loading...';
});
try {
PaymentMethod paymentMethod =
await _ansaFlutterSdk.customer.addPaymentMethod(
customerId: _customerId,
paymentMethodType: StripePaymentMethod(
paymentMethodId: paymentMethodId,
),
idempotencyKey: 'test_add_payment_method',
);
setState(() {
_result = '''
Payment Method ID: ${paymentMethod.id}
Type: ${paymentMethod.type}
Card Brand: ${paymentMethod.card.brand}
Fingerprint: ${paymentMethod.card.fingerprint}
First Six: ${paymentMethod.card.firstSix}
Last Four: ${paymentMethod.card.lastFour}
''';
});
} catch (e) {
setState(() {
_result = 'Failed to add payment method. Please try again.';
});
}
}
Future<void> _deletePaymentMethod() async {
setState(() {
_result = 'Loading...';
});
try {
List<PaymentMethod> paymentMethods = await _ansaFlutterSdk.customer
.getPaymentMethods(customerId: _customerId);
if (paymentMethods.isNotEmpty) {
await _ansaFlutterSdk.customer.deletePaymentMethod(
customerId: _customerId,
paymentMethodId: paymentMethods.first.id,
idempotencyKey: 'test_delete_payment_method',
);
setState(() {
_result = 'Payment method deleted successfully.';
});
} else {
setState(() {
_result = 'No payment methods found to delete.';
});
}
} catch (e) {
setState(() {
_result = 'Failed to delete payment method. Please try again.';
});
}
}
Future<void> _getAutoReloadConfiguration() async {
setState(() {
_result = 'Loading...';
});
try {
AutoReloadConfig autoReloadConfig =
await _ansaFlutterSdk.customer.getAutoReloadConfiguration(
customerId: _customerId,
);
setState(() {
_result = '''
Enabled: ${autoReloadConfig.enabled}
Payment Method ID: ${autoReloadConfig.paymentMethodId}
Reload Amount: ${autoReloadConfig.reloadAmount}
Reload Threshold: ${autoReloadConfig.reloadThreshold}
''';
});
} catch (e) {
setState(() {
_result =
'Failed to fetch auto reload configuration. Please try again.';
});
}
}
Future<void> _setAutoReloadConfiguration() async {
setState(() {
_result = 'Loading...';
});
try {
var request = AutoReloadConfigurationRequest(
customerId: _customerId,
enabled: true,
paymentMethodId: 'a8a83792-03d1-4a55-acff-8770a6ad01da',
reloadAmount: 5000,
reloadThreshold: 1000,
);
AutoReloadConfig autoReloadConfig = await _ansaFlutterSdk.customer
.setAutoReloadConfiguration(request: request);
setState(() {
_result = '''
Enabled: ${autoReloadConfig.enabled}
Payment Method ID: ${autoReloadConfig.paymentMethodId}
Reload Amount: ${autoReloadConfig.reloadAmount}
Reload Threshold: ${autoReloadConfig.reloadThreshold}
''';
});
} catch (e) {
setState(() {
_result = 'Failed to set auto reload configuration. Please try again.';
});
}
}
Future<void> _addBalance() async {
setState(() {
_result = 'Loading...';
});
try {
var request = AddBalanceRequest(
customerId: _customerId,
amount: 5000,
paymentMethodId: 'a8a83792-03d1-4a55-acff-8770a6ad01da',
);
final balanceUpdate = await _ansaFlutterSdk.customer.addBalance(
request: request,
idempotencyKey: 'test_add_balance',
);
setState(() {
_result = '''
Balance: ${balanceUpdate.balance.amount} ${balanceUpdate.balance.currency}
Transaction ID: ${balanceUpdate.transactionId}
''';
});
} catch (e) {
setState(() {
_result = 'Failed to add balance. Please try again.';
});
}
}
Future<void> _useBalance() async {
setState(() {
_result = 'Loading...';
});
try {
var request = UseBalanceRequest(customerId: _customerId, amount: 1000);
final balanceUpdate = await _ansaFlutterSdk.customer.useBalance(
request: request,
idempotencyKey: 'test_use_balance',
);
setState(() {
_result = '''
Balance: ${balanceUpdate.balance.amount} ${balanceUpdate.balance.currency}
Transaction ID: ${balanceUpdate.transactionId}
''';
});
} catch (e) {
setState(() {
_result = 'Failed to use balance. Please try again.';
});
}
}
Future<void> _getAppReloadConfig() async {
setState(() {
_result = 'Loading...';
});
try {
var config = await _ansaFlutterSdk.customer
.getAppReloadConfig(customerId: _customerId);
setState(() {
_result = '''
Allow Custom Amount: ${config.allowCustomAmount}
Preset Amounts: ${config.presetAmounts.join(', ')}
''';
});
} catch (e) {
setState(() {
_result = 'Failed to fetch app reload configuration. Please try again.';
});
}
}
Future<void> _getTransactions() async {
setState(() {
_result = 'Loading...';
});
try {
var transactions = await _ansaFlutterSdk.customer
.getTransactions(customerId: _customerId);
setState(() {
_result = transactions.transactions.map((transaction) {
return '''
Transaction ID: ${transaction.id}
Amount: ${transaction.amount}
Created At: ${transaction.createdAt}
''';
}).join('\n');
});
} catch (e) {
setState(() {
_result = 'Failed to fetch transactions. Please try again.';
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Ansa Flutter SDK Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: SingleChildScrollView(
child: Column(
children: [
const SizedBox(height: 20),
const Text(
'Ansa Example App (Flutter)',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(height: 20),
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: _fetchCardArtUrls,
child: const Text('Fetch Card Art'),
),
ElevatedButton(
onPressed: _fetchCustomer,
child: const Text('Fetch Customer'),
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: _fetchMerchant,
child: const Text('Fetch Merchant'),
),
ElevatedButton(
onPressed: _fetchPaymentMethods,
child: const Text('Fetch Payment Methods'),
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: _addPaymentMethod,
child: const Text('Add Payment Method'),
),
ElevatedButton(
onPressed: _deletePaymentMethod,
child: const Text('Delete Payment Method'),
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: _getAutoReloadConfiguration,
child: const Text('Fetch Auto Reload'),
),
ElevatedButton(
onPressed: _setAutoReloadConfiguration,
child: const Text('Set Auto Reload'),
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: _addBalance,
child: const Text('Add Balance'),
),
ElevatedButton(
onPressed: _useBalance,
child: const Text('Use Balance'),
),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: _getTransactions,
child: const Text('Fetch Transactions'),
),
ElevatedButton(
onPressed: _getAppReloadConfig,
child: const Text('Fetch App Reload'),
),
],
),
],
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ManagedAnsaBalanceScreen(
customerId: _customerId,
merchantId: _merchantId,
),
),
);
},
child: const Text('Open Balance Screen with Navigator'),
),
const SizedBox(height: 20),
Text(
_result,
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
],
),
),
),
),
);
}
}