cofee_payment_flutter 1.0.3
cofee_payment_flutter: ^1.0.3 copied to clipboard
This SDK provides a simple way to integrate CoFee Payment into your Flutter applications. It handles the payment flow, including opening the payment page and monitoring for completion. It then calls a [...]
example/lib/main.dart
import 'package:cofee_payment_flutter/entities/payment_details_entity.dart';
import 'package:cofee_payment_flutter/exceptions/payment_exceptions.dart';
import 'package:flutter/material.dart';
import 'package:cofee_payment_flutter/cofee_payment.dart';
/// Main entry point for the CoFee Payment SDK example application.
///
/// This example demonstrates how to integrate and use the CoFee Payment SDK
/// in a Flutter application, including error handling and UI feedback.
void main() {
runApp(const CoffeePaymentTestApp());
}
/// The root widget of the CoFee Payment example application.
///
/// This widget sets up the MaterialApp with a custom theme and
/// the payment demonstration page as the home screen.
class CoffeePaymentTestApp extends StatelessWidget {
const CoffeePaymentTestApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'CoFee Payment Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
useMaterial3: true,
),
home: const PaymentPage(),
);
}
}
/// A demonstration page showing how to implement CoFee Payment SDK.
///
/// This page provides a complete example of:
/// - Configuring the SDK with client ID and environment
/// - Initiating payments with proper error handling
/// - Providing user feedback during the payment process
/// - Handling various payment outcomes (success/failure)
class PaymentPage extends StatefulWidget {
const PaymentPage({super.key});
@override
State<PaymentPage> createState() => _PaymentPageState();
}
class _PaymentPageState extends State<PaymentPage> {
// Text controllers for user input
final TextEditingController _orderIdController =
TextEditingController(text: 'ord_j23ngec8uL8613_test');
final TextEditingController _clientIdController =
TextEditingController(text: 'TEST_client_id');
// Toggle for sandbox/production environment
bool isSandbox = true;
// UI state variables
bool _isLoading = false;
String _statusMessage = '';
@override
void dispose() {
// Clean up controllers when the widget is disposed
_orderIdController.dispose();
_clientIdController.dispose();
super.dispose();
}
void clearStatusMessage() {
setState(() {
_statusMessage = "";
});
}
@override
void initState() {
_clientIdController.addListener(() {
clearStatusMessage();
});
_orderIdController.addListener(() {
clearStatusMessage();
});
super.initState();
}
/// Initiates the payment process with proper error handling.
///
/// This method:
/// 1. Validates the user input (order ID)
/// 2. Creates a CoFeePayment instance with the provided configuration
/// 3. Initiates the payment process
/// 4. Handles success and error cases
/// 5. Updates the UI to reflect the payment status
Future<void> _initiatePayment() async {
final orderId = _orderIdController.text.trim();
// Initialize the SDK with the provided configuration
final CoFeePayment coFeePayment = CoFeePayment(
clientId: _clientIdController.text,
paymentEnvironment: isSandbox
? PaymentEnvironment.sandbox
: PaymentEnvironment.production,
);
// Validate the order ID
if (orderId.isEmpty) {
setState(() {
_statusMessage = 'Please enter a valid order ID';
});
return;
}
// Show loading state
setState(() {
_isLoading = true;
_statusMessage = 'Processing payment...';
});
try {
// Initiate the payment process
await coFeePayment.pay(
orderId,
onFinish: () {
// Handle successful payment completion
setState(() {
_isLoading = false;
_statusMessage = 'Payment flow completed. Please check the status';
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(_statusMessage)),
);
},
onError: (PaymentException error) {
// Handle payment errors with specific messages
setState(() {
_isLoading = false;
switch (error.errorType) {
case PaymentErrorType.invalidOrderId:
_statusMessage =
'Error: Please check the order ID and try again';
break;
case PaymentErrorType.network:
_statusMessage = 'Error: Please check your internet connection';
break;
case PaymentErrorType.api:
_statusMessage =
'Error: Payment service error: ${error.message}';
break;
case PaymentErrorType.invalidResponse:
_statusMessage = 'Error: Invalid response from payment service';
break;
case PaymentErrorType.unknown:
_statusMessage = 'Error: An unexpected error occurred';
break;
}
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(_statusMessage)),
);
},
);
} catch (e) {
// Handle any unexpected errors
setState(() {
_isLoading = false;
_statusMessage = 'An unexpected error occurred. Please try again.';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'',
style: Theme.of(context).textTheme.titleLarge,
),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Coffee icon
Image.asset(
"assets/images/logo.png",
width: 80,
height: 80,
),
const SizedBox(height: 16),
// Coffee price title
const Text(
'Coffee Payment',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
// Coffee price
const Text(
'Test',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 24),
TextField(
controller: _clientIdController,
decoration: const InputDecoration(
labelText: 'Client Token',
border: OutlineInputBorder(),
hintText: 'Client token',
),
),
const SizedBox(height: 16),
Row(
children: [
Text("isSandbox"),
Switch(
value: isSandbox,
onChanged: (v) {
setState(() {
isSandbox = v;
});
}),
],
),
const SizedBox(height: 16),
// Order ID text field
TextField(
controller: _orderIdController,
decoration: const InputDecoration(
labelText: 'Order ID',
border: OutlineInputBorder(),
hintText: 'Enter the order ID',
),
),
const SizedBox(height: 16),
// Status message
if (_statusMessage.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Text(
_statusMessage,
style: TextStyle(
color: _statusMessage.startsWith('Error')
? Colors.red
: Colors.green,
),
textAlign: TextAlign.center,
),
),
// Pay button
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isLoading ? null : _initiatePayment,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: _isLoading
? const CircularProgressIndicator()
: const Text(
'Pay Now',
style: TextStyle(fontSize: 16),
),
),
),
],
),
),
),
),
);
}
}