addInvoice method

Future<PaylinkInvoice> addInvoice({
  1. required double amount,
  2. required String clientMobile,
  3. required String clientName,
  4. String? clientEmail,
  5. required String orderNumber,
  6. required String callBackUrl,
  7. String? cancelUrl,
  8. String? currency = "SAR",
  9. required List<PaylinkProduct> products,
  10. String? note,
  11. String? smsMessage,
  12. List<String>? supportedCardBrands,
  13. bool displayPending = true,
})

Adds an invoice to the Paylink system.

Implementation

Future<PaylinkInvoice> addInvoice({
  required double amount,
  required String clientMobile,
  required String clientName,
  String? clientEmail,
  required String orderNumber,
  required String callBackUrl,
  String? cancelUrl,
  String? currency = "SAR",
  required List<PaylinkProduct> products,
  String? note,
  String? smsMessage,
  List<String>? supportedCardBrands,
  bool displayPending = true,
}) async {
  try {
    if (idToken == null) await _authenticate();

    /// Filter and sanitize supportedCardBrands
    if (supportedCardBrands != null && supportedCardBrands.isNotEmpty) {
      supportedCardBrands = supportedCardBrands
          .where((brand) => PaylinkConstants.validCardBrands.contains(brand))
          .toList();
    }

    /// Convert PaylinkProduct objects to maps
    List<Map<String, dynamic>> productsArray = [];
    if (products.isNotEmpty) {
      for (var product in products) {
        productsArray.add(product.toMap());
      }
    }

    /// Request body parameters
    Map<String, dynamic> requestBody = {
      'amount': amount,
      'callBackUrl': callBackUrl,
      'cancelUrl': cancelUrl,
      'clientEmail': clientEmail,
      'clientMobile': clientMobile,
      'currency': currency,
      'clientName': clientName,
      'note': note,
      'orderNumber': orderNumber,
      'products': productsArray,
      'smsMessage': smsMessage,
      'supportedCardBrands': supportedCardBrands,
      'displayPending': displayPending,
    };

    final response = await http.post(
      Uri.parse('$apiBaseUrl/api/addInvoice'),
      headers: {
        'accept': '*/*',
        'content-type': 'application/json',
        'Authorization': 'Bearer $idToken',
      },
      body: jsonEncode(requestBody),
    );

    if (response.statusCode != 200) {
      _handleResponseError(response, 'Failed to add the invoice');
    }

    /// Decode the JSON response and extract the order details
    final orderDetails = json.decode(response.body);

    if (orderDetails is! Map<String, dynamic>) {
      throw Exception('Order details missing from the response');
    }

    return PaylinkInvoice.fromResponseData(orderDetails);
  } catch (e) {
    rethrow;
  }
}