createDiscount method

Future<Map<String, dynamic>> createDiscount({
  1. required String name,
  2. required String code,
  3. required int amount,
  4. required String amountType,
  5. int? storeId,
  6. bool isLimitedToProducts = false,
  7. bool isLimitedRedemptions = false,
  8. int maxRedemptions = 0,
  9. String? startsAt,
  10. String? expiresAt,
  11. String duration = "once",
  12. int durationInMonths = 1,
  13. bool testMode = false,
  14. List<int>? variantIds,
})

Implementation

Future<Map<String, dynamic>> createDiscount({
  required String name,
  required String code,
  required int amount,
  required String amountType,
  int? storeId,
  bool isLimitedToProducts = false,
  bool isLimitedRedemptions = false,
  int maxRedemptions = 0,
  String? startsAt,
  String? expiresAt,
  String duration = "once",
  int durationInMonths = 1,
  bool testMode = false,
  List<int>? variantIds,
}) async {
  if (apiKey.isEmpty) {
    return {'error': 'API key is empty'};
  }

  final Map<String, dynamic> data = {
    'data': {
      'type': 'discounts',
      'attributes': {
        'name': name,
        'code': code,
        'amount': amount,
        'amount_type': amountType,
        'is_limited_to_products': isLimitedToProducts,
        'is_limited_redemptions': isLimitedRedemptions,
        'max_redemptions': maxRedemptions,
        'starts_at': startsAt,
        'expires_at': expiresAt,
        'duration': duration,
        'duration_in_months': durationInMonths,
        'test_mode': testMode,
      },
      'relationships': {
        'store': {
          'data': {
            'type': 'stores',
            'id': storeId.toString(),
          }
        }
      }
    }
  };

  if (variantIds != null && isLimitedToProducts) {
    data['data']['relationships']['variants'] = {
      'data': variantIds
          .map((id) => {'type': 'variants', 'id': id.toString()})
          .toList(),
    };
  }

  Options dioOptions = Options(
    headers: {
      "Authorization": "Bearer $apiKey",
      "Accept": "application/vnd.api+json",
      "Content-Type": "application/vnd.api+json",
    },
  );

  try {
    Response response = await dio.post(
      "https://api.lemonsqueezy.com/v1/discounts",
      options: dioOptions,
      data: data,
    );

    return response.data;
  } catch (e) {
    return {'error': e.toString()};
  }
}