Discount API
The Discount API allows you to create, verify, and manage discount codes and promotional campaigns in your Flutter application.
Overview
The discount module provides methods to:
- 🎫 Get available discounts - Retrieve all active discount codes
- ✅ Verify discount codes - Validate discount applicability
- 📊 Manage promotions - Handle promotional campaigns
Get Available Discounts
Retrieve all available discount codes and promotions.
Method
Get Discounts
Future<List<Discount>> get()
Example
lib/services/discount_service.dart
import 'package:your_app/services/sdk_service.dart';
class DiscountService {
static Future<List<Discount>> getAvailableDiscounts() async {
try {
final discounts = await SdkService().sdk.discount.get();
print('Found ${discounts.length} available discounts');
for (final discount in discounts) {
print('Discount: ${discount.code} - ${discount.description}');
print('Value: ${discount.value}% off');
}
return discounts;
} catch (e) {
print('Error fetching discounts: $e');
return [];
}
}
}
Response Format
Discount Model
class Discount {
final String id;
final String code;
final String description;
final double value;
final String type; // 'percentage' | 'fixed'
final DateTime? expiresAt;
final bool isActive;
final double? minimumAmount;
// Convert to JSON
Map<String, dynamic> toJson();
}
Verify Discount Code
Validate if a discount code can be applied to a specific cart or checkout.
Method
Verify Discount
Future<DiscountValidation> verify({
required String code,
required String cartId,
})
Example
lib/screens/checkout_screen.dart
class CheckoutScreen extends StatefulWidget {
final String cartId;
const CheckoutScreen({super.key, required this.cartId});
_CheckoutScreenState createState() => _CheckoutScreenState();
}
class _CheckoutScreenState extends State<CheckoutScreen> {
final _discountController = TextEditingController();
String? _discountMessage;
bool _isValidDiscount = false;
Future<void> _verifyDiscount() async {
final code = _discountController.text.trim();
if (code.isEmpty) return;
try {
final validation = await SdkService().sdk.discount.verify(
code: code,
cartId: widget.cartId,
);
setState(() {
_isValidDiscount = validation.isValid;
_discountMessage = validation.message;
});
if (validation.isValid) {
// Apply discount to cart
await _applyDiscountToCart(code);
}
} catch (e) {
setState(() {
_isValidDiscount = false;
_discountMessage = 'Invalid discount code';
});
}
}
Future<void> _applyDiscountToCart(String code) async {
// Implementation to apply discount
print('Applying discount: $code');
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Checkout')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _discountController,
decoration: InputDecoration(
labelText: 'Discount Code',
suffixIcon: IconButton(
icon: const Icon(Icons.check),
onPressed: _verifyDiscount,
),
),
),
if (_discountMessage != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
_discountMessage!,
style: TextStyle(
color: _isValidDiscount ? Colors.green : Colors.red,
),
),
),
],
),
),
);
}
}
Apply Discount to Cart
Apply a verified discount code to a shopping cart.
Method
Apply Discount
Future<Cart> applyDiscount({
required String cartId,
required String discountCode,
})
Example
lib/services/cart_service.dart
class CartService {
static Future<Cart?> applyDiscountToCart({
required String cartId,
required String discountCode,
}) async {
try {
// First verify the discount
final validation = await SdkService().sdk.discount.verify(
code: discountCode,
cartId: cartId,
);
if (!validation.isValid) {
throw Exception('Invalid discount code: ${validation.message}');
}
// Apply the discount
final updatedCart = await SdkService().sdk.discount.applyDiscount(
cartId: cartId,
discountCode: discountCode,
);
print('Discount applied successfully!');
print('New total: \$${updatedCart.total}');
print('Discount amount: \$${updatedCart.discountAmount}');
return updatedCart;
} catch (e) {
print('Error applying discount: $e');
return null;
}
}
}
Remove Discount
Remove an applied discount from a cart.
Method
Remove Discount
Future<Cart> removeDiscount({
required String cartId,
})
Example
Remove Discount Example
Future<void> removeDiscountFromCart(String cartId) async {
try {
final updatedCart = await SdkService().sdk.discount.removeDiscount(
cartId: cartId,
);
print('Discount removed successfully!');
print('New total: \$${updatedCart.total}');
} catch (e) {
print('Error removing discount: $e');
}
}
Error Handling
Handle common discount-related errors:
Error Handling Example
Future<void> handleDiscountErrors() async {
try {
final discounts = await SdkService().sdk.discount.get();
// Process discounts...
} on DiscountException catch (e) {
switch (e.type) {
case DiscountErrorType.expired:
print('Discount code has expired');
break;
case DiscountErrorType.notFound:
print('Discount code not found');
break;
case DiscountErrorType.minimumNotMet:
print('Minimum purchase amount not met');
break;
case DiscountErrorType.alreadyUsed:
print('Discount code already used');
break;
default:
print('Discount error: ${e.message}');
}
} catch (e) {
print('General error: $e');
}
}
Best Practices
1. Cache Discount Data
Caching Example
class DiscountCache {
static List<Discount>? _cachedDiscounts;
static DateTime? _lastFetch;
static Future<List<Discount>> getDiscounts() async {
final now = DateTime.now();
// Cache for 5 minutes
if (_cachedDiscounts != null &&
_lastFetch != null &&
now.difference(_lastFetch!).inMinutes < 5) {
return _cachedDiscounts!;
}
_cachedDiscounts = await SdkService().sdk.discount.get();
_lastFetch = now;
return _cachedDiscounts!;
}
}
2. Real-time Validation
Real-time Validation
class DiscountInput extends StatefulWidget {
final Function(String) onValidDiscount;
const DiscountInput({super.key, required this.onValidDiscount});
_DiscountInputState createState() => _DiscountInputState();
}
class _DiscountInputState extends State<DiscountInput> {
final _controller = TextEditingController();
Timer? _debounceTimer;
void initState() {
super.initState();
_controller.addListener(_onDiscountChanged);
}
void _onDiscountChanged() {
_debounceTimer?.cancel();
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
_validateDiscount(_controller.text);
});
}
Future<void> _validateDiscount(String code) async {
if (code.length >= 3) {
// Validate discount code
// Call widget.onValidDiscount if valid
}
}
Widget build(BuildContext context) {
return TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'Discount Code',
hintText: 'Enter your discount code',
),
);
}
}
Related APIs
- Cart API - Apply discounts to shopping carts
- Checkout API - Use discounts during checkout
- Payment API - Process payments with discounts
Troubleshooting
Common Issues
-
"Discount code not found"
- Verify the code spelling
- Check if the discount is still active
- Ensure the discount applies to your market/channel
-
"Minimum amount not met"
- Check the cart total against discount requirements
- Add more items if needed
-
"Discount expired"
- Verify the discount expiration date
- Use
get()
to fetch active discounts only
-
"Already used"
- Some discounts are single-use per customer
- Check discount usage limits