polybrainz_now_payments 1.0.1 copy "polybrainz_now_payments: ^1.0.1" to clipboard
polybrainz_now_payments: ^1.0.1 copied to clipboard

A type-safe Dart API wrapper for NOWPayments cryptocurrency payment gateway. Accept 300+ cryptocurrencies with payments, invoices, payouts, and IPN webhooks.

example/polybrainz_now_payments_example.dart

import 'package:polybrainz_now_payments/polybrainz_now_payments.dart';

void main() async {
  // Initialize the client
  final client = NowPaymentsClient(
    config: NowPaymentsConfig(
      apiKey: 'YOUR_API_KEY',
      environment: NowPaymentsEnvironment.sandbox, // Use sandbox for testing
      logger: print, // Optional: enable debug logging
    ),
  );

  try {
    // ═══════════════════════════════════════════════════════════════════════
    // Check API Status
    // ═══════════════════════════════════════════════════════════════════════
    final status = await client.getStatus();
    print('API Status: ${status.message} (OK: ${status.isOk})');

    // ═══════════════════════════════════════════════════════════════════════
    // Get Available Currencies
    // ═══════════════════════════════════════════════════════════════════════
    final currencies = await client.getCurrencies();
    print('Available currencies: ${currencies.take(10).join(", ")}...');

    // ═══════════════════════════════════════════════════════════════════════
    // Get Minimum Payment Amount
    // ═══════════════════════════════════════════════════════════════════════
    final minimum = await client.getMinimumPaymentAmount(
      currencyFrom: 'btc',
      currencyTo: 'usd',
    );
    print('Minimum BTC payment: ${minimum.minAmount} BTC');

    // ═══════════════════════════════════════════════════════════════════════
    // Get Estimated Price
    // ═══════════════════════════════════════════════════════════════════════
    final estimate = await client.getEstimatePrice(
      amount: 100,
      currencyFrom: 'usd',
      currencyTo: 'btc',
    );
    print('100 USD = ${estimate.estimatedAmount} BTC');

    // ═══════════════════════════════════════════════════════════════════════
    // Create a Payment
    // ═══════════════════════════════════════════════════════════════════════
    final payment = await client.createPayment(
      CreatePaymentRequest(
        priceAmount: 100.0,
        priceCurrency: FiatCurrency.usd,
        payCurrency: 'btc',
        orderId: 'ORDER-${DateTime.now().millisecondsSinceEpoch}',
        orderDescription: 'Test payment for premium subscription',
        ipnCallbackUrl: 'https://yoursite.com/webhook/nowpayments',
      ),
    );

    print('');
    print('Payment created successfully!');
    print('  Payment ID: ${payment.paymentId}');
    print('  Pay Address: ${payment.payAddress}');
    print('  Amount: ${payment.payAmount} ${payment.payCurrency.toUpperCase()}');
    print('  Status: ${payment.paymentStatus}');

    // ═══════════════════════════════════════════════════════════════════════
    // Check Payment Status
    // ═══════════════════════════════════════════════════════════════════════
    final updatedPayment = await client.getPaymentStatus(payment.paymentId);
    print('');
    print('Payment status check:');
    print('  Status: ${updatedPayment.paymentStatus}');
    print('  Is Pending: ${updatedPayment.isPending}');
    print('  Is Complete: ${updatedPayment.isComplete}');

    // ═══════════════════════════════════════════════════════════════════════
    // Create an Invoice
    // ═══════════════════════════════════════════════════════════════════════
    final invoice = await client.createInvoice(
      CreateInvoiceRequest(
        priceAmount: 50.0,
        priceCurrency: FiatCurrency.eur,
        orderId: 'INV-${DateTime.now().millisecondsSinceEpoch}',
        orderDescription: 'Invoice for consulting services',
        successUrl: 'https://yoursite.com/payment/success',
        cancelUrl: 'https://yoursite.com/payment/cancel',
      ),
    );

    print('');
    print('Invoice created successfully!');
    print('  Invoice ID: ${invoice.id}');
    print('  Invoice URL: ${invoice.invoiceUrl}');

    // ═══════════════════════════════════════════════════════════════════════
    // List Payments
    // ═══════════════════════════════════════════════════════════════════════
    final paymentsList = await client.getPayments(
      ListPaymentsRequest(
        limit: 5,
        page: 0,
        orderBy: SortOrder.desc,
      ),
    );

    print('');
    print('Recent payments (${paymentsList.total} total):');
    for (final p in paymentsList.data) {
      print(
        '  - ${p.paymentId}: ${p.paymentStatus} '
        '(${p.priceAmount} ${p.priceCurrency})',
      );
    }
  } on AuthenticationException catch (e) {
    print('Authentication error: ${e.message}');
  } on BadRequestException catch (e) {
    print('Bad request: ${e.message}');
  } on NotFoundException catch (e) {
    print('Not found: ${e.message}');
  } on RateLimitException catch (e) {
    print('Rate limited: ${e.message}');
  } on NowPaymentsException catch (e) {
    print('API error (${e.statusCode}): ${e.message}');
  } finally {
    client.dispose();
  }
}

// ═══════════════════════════════════════════════════════════════════════════
// IPN Webhook Handler Example
// ═══════════════════════════════════════════════════════════════════════════
void handleIpnCallback(Map<String, String> headers, String body) {
  // import 'dart:convert';
  // final payload = jsonDecode(body) as Map<String, dynamic>;

  const ipnSecretKey = 'YOUR_IPN_SECRET_KEY';
  final validator = IpnValidator(ipnSecretKey);

  final signature = headers['x-nowpayments-sig'];
  if (signature == null) {
    print('Missing signature header');
    return;
  }

  // Parse and validate the payload
  // final payment = validator.parseIpnPayload(
  //   signature: signature,
  //   payload: payload,
  // );

  // if (payment == null) {
  //   print('Invalid IPN signature');
  //   return;
  // }

  // Handle payment status
  // switch (payment.paymentStatus) {
  //   case PaymentStatus.finished:
  //     print('Payment ${payment.paymentId} completed!');
  //     // Update order status in database
  //     break;
  //   case PaymentStatus.failed:
  //   case PaymentStatus.expired:
  //     print('Payment ${payment.paymentId} failed/expired');
  //     // Handle failed payment
  //     break;
  //   case PaymentStatus.partiallyPaid:
  //     print('Payment ${payment.paymentId} partially paid');
  //     // Notify user of partial payment
  //     break;
  //   default:
  //     print('Payment ${payment.paymentId} status: ${payment.paymentStatus}');
  // }

  print('IPN validator ready with key: $ipnSecretKey');
  print('Signature received: $signature');
  print('Validator: $validator');
}
0
likes
160
points
191
downloads

Publisher

verified publisherpolybrainz.bot

Weekly Downloads

A type-safe Dart API wrapper for NOWPayments cryptocurrency payment gateway. Accept 300+ cryptocurrencies with payments, invoices, payouts, and IPN webhooks.

Homepage
Repository (GitHub)
View/report issues

Topics

#payments #cryptocurrency #api-wrapper #bitcoin #fintech

Documentation

API reference

License

MIT (license)

Dependencies

crypto, http

More

Packages that depend on polybrainz_now_payments