# Flutter SDK

Take crypto payments inside your Flutter app. The checkout opens as a full-screen native screen in your app, with
no browser bar. The customer picks a network and a coin, scans the QR or taps "Open in MetaMask / Trust", and sees
a green success screen. Your code gets a typed result back.

- **Package:** [`razcrypto_checkout`](https://pub.dev/packages/razcrypto_checkout) on pub.dev
- **Version:** 1.0.0
- **Platforms:** Android and iOS
- **Requires:** Flutter 3.24+, Dart 3.5+
- **Key in the app:** none (opens the `checkout_url` from your server), or the publishable key `pk_…`
- **Download:** [razcrypto-flutter-sdk.zip](https://razcryptogateway.com/downloads/razcrypto-flutter-sdk.zip) · [Source on GitHub](https://github.com/WorldxGrowth/razcrypto-flutter-sdk) · MIT

## How it works

1. The app asks **your server** to start a payment.
2. Your server creates the payment with its **secret key** and returns the `checkout_url`.
3. The app opens the checkout with the SDK.
4. The customer pays. The SDK returns `CheckoutSuccess`, `CheckoutPending`, `CheckoutCancelled` or `CheckoutFailed`.
5. The app sends the result to your server. The server checks the signature and asks RazCrypto for the status.
6. RazCrypto also sends the signed `payment.paid` webhook to your server. **Only the server marks the order paid.**

The secret key (`sk_…`) and the webhook signing secret (`whsec_…`) stay on your server. They never go in the app.

## 1. Get your keys

In the dashboard:

1. **Wallets**: add and turn on the wallet that should receive the coins, and pick the coins.
2. **API apps** → create an app. You get:
   - **Publishable key** `pk_test_…` / `pk_live_…` (safe in an app; optional)
   - **Secret key** `sk_test_…` / `sk_live_…` (server only)
   - **Webhook signing secret** `whsec_…` (server only)
3. Set the app's **Webhook URL** to your server, for example `https://api.yourapp.com/api/webhooks/razcrypto`.

Build with the `test` keys first. Test mode never moves real money.

## 2. Install

### From pub.dev (recommended)

```bash
flutter pub add razcrypto_checkout
```

This adds the package to `pubspec.yaml`:

```yaml
dependencies:
  razcrypto_checkout: ^1.0.0
```

### From the download (local / offline)

Use this when your build machine has no access to pub.dev, or you want to keep a copy in your repository.

```bash
# from your Flutter project root
mkdir -p packages/razcrypto_checkout
curl -L -o razcrypto-flutter-sdk.zip https://razcryptogateway.com/downloads/razcrypto-flutter-sdk.zip
unzip razcrypto-flutter-sdk.zip -d packages/razcrypto_checkout
```

```yaml
# pubspec.yaml
dependencies:
  razcrypto_checkout:
    path: packages/razcrypto_checkout
```

Then run `flutter pub get`. Check the file against the SHA-256 in [manifest.json](https://razcryptogateway.com/downloads/manifest.json).

### From GitHub (development)

```yaml
dependencies:
  razcrypto_checkout:
    git:
      url: https://github.com/WorldxGrowth/razcrypto-flutter-sdk.git
      ref: v1.0.0
```

### Android setup

Release builds need the internet permission in `android/app/src/main/AndroidManifest.xml`. Most apps already have
it (Razorpay, Firebase and HTTP calls need it too):

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application ...>
```

Nothing else is needed. iOS needs no extra setup either.

## 3. Server: create the payment

Your server creates the payment and returns `payment_id` and `checkout_url` to the app. Use the SDK for your
backend: [PHP / Laravel](/docs/php-sdk), [Node.js](/docs/node-sdk) or [Python](/docs/python-sdk).

```php
// Laravel (composer require worldxgrowth/razcrypto-php-sdk)
$rc = new \RazCrypto\Client(config('services.razcrypto.secret_key')); // sk_test_… / sk_live_…

$payment = $rc->payments()->create([
    'amount'       => number_format($order->amount, 2, '.', ''), // "499.00" (string)
    'currency'     => 'INR',                                     // converted to crypto at checkout
    'reference_id' => (string) $order->id,
], 'order_' . $order->id); // idempotency key: a retry never creates a second payment

return ['payment_id' => $payment['id'], 'checkout_url' => $payment['checkout_url']];
```

```js
// Node.js (npm install razcrypto-node)
const payment = await rc.payments.create(
  { amount: order.amount.toFixed(2), currency: 'INR', reference_id: String(order.id) },
  { idempotencyKey: `order_${order.id}` },
);
res.json({ payment_id: payment.id, checkout_url: payment.checkout_url });
```

## 4. App: open the checkout

```dart
import 'package:flutter/material.dart';
import 'package:razcrypto_checkout/razcrypto_checkout.dart';

Future<void> payWithCrypto(BuildContext context, int amount) async {
  // 1. Ask your server to create the payment
  final order = await api.post('/payments/razcrypto/create', body: {'amount': amount});
  final checkoutUrl = order['checkout_url'] as String;
  if (!context.mounted) return;

  // 2. Open the checkout (full screen, inside your app)
  final result = await RazCryptoCheckout.open(
    context,
    CheckoutOptions.fromCheckoutUrl(checkoutUrl, locale: 'en'), // 'hi' for Hindi
  );
  if (!context.mounted) return;

  // 3. Handle the result
  switch (result) {
    case CheckoutSuccess(:final paymentId, :final referenceId, :final status, :final signature):
      final res = await api.post('/payments/razcrypto/verify', body: {
        'payment_id': paymentId,
        'reference_id': referenceId,
        'status': status,
        'signature': signature ?? '',
      });
      await waitForPaid(context, res['status'] as String, paymentId);

    case CheckoutPending(:final paymentId):
      // The transfer is on-chain and waiting for confirmations
      await waitForPaid(context, 'pending', paymentId);

    case CheckoutCancelled():
      // The customer closed the checkout. The order stays pending; they can pay later.
      break;

    case CheckoutFailed(:final message):
      showSnack(context, message.isEmpty ? 'Payment failed' : message);
  }
}
```

**Using the publishable key instead of the URL.** If your server returns only the payment id:

```dart
CheckoutOptions(key: 'pk_live_…', paymentId: 'pay_…') // never a secret key: the SDK refuses sk_…
```

### Wait for "paid" while the payment confirms

On-chain confirmations take from a few seconds to a few minutes. Poll your server for a short while. If it is still
confirming, tell the customer; the webhook will finish the order later.

```dart
Future<void> waitForPaid(BuildContext context, String status, String paymentId) async {
  var st = status;
  for (var i = 0; i < 6 && st != 'completed' && st != 'failed'; i++) {
    await Future<void>.delayed(const Duration(seconds: 5));
    try {
      st = (await api.get('/payments/razcrypto/status/$paymentId'))['status'] as String;
    } catch (_) {/* network hiccup: try again */}
  }
  if (!context.mounted) return;
  // Refresh the order / wallet from your server here: the server is the source of truth.
  showSnack(context, switch (st) {
    'completed' => 'Payment successful',
    'failed' => 'Payment failed',
    _ => 'Payment is confirming. We will update your order shortly.',
  });
}
```

## 5. Server: verify and fulfil

Three endpoints finish the flow. The full Laravel code (routes, controller, migration) is on the
[PHP SDK page](/docs/php-sdk#laravel-full-integration-for-a-mobile-app).

| Endpoint | What it does |
|---|---|
| `POST /payments/razcrypto/verify` | Checks the checkout `signature` with the webhook signing secret, then calls `payments.retrieve(id)`. Marks the order paid only if the status is `paid`. |
| `GET /payments/razcrypto/status/{id}` | Returns `completed`, `pending` or `failed` for polling. |
| `POST /webhooks/razcrypto` | Verifies the [webhook](/docs/webhooks) and marks the order paid on `payment.paid`. Must be idempotent. |

`signature` = hex HMAC-SHA256(webhook signing secret, `payment_id|reference_id|status`). Every server SDK checks
it for you (`CheckoutSignature::isValid`, `isValidCheckoutSignature`, `is_valid_checkout_signature`).

## 6. Show the option from your admin panel

Do not hard-code the payment methods in the app. Let the server return the list, so the admin can turn crypto on
or off without an app update:

```dart
final gateways = await api.get('/payment-gateways'); // e.g. [{gateway: 'razorpay', ...}, {gateway: 'razcrypto', display_name: 'Pay with Crypto'}]
```

In your admin panel, store per environment: on/off, mode (test/live), publishable key, secret key and webhook
signing secret (encrypted, shown masked), and a display name.

## What the customer sees

- A full-screen checkout in your app with your logo and colours, no address bar.
- Network → coin → QR code and amount, or "Open in MetaMask / Trust" (the wallet app opens; the payment stays open).
- A live status: waiting → confirming → green success screen. The screen then closes by itself.
- Android Back asks "Leave this payment?" before closing.
- New coins, networks and design updates arrive without an app update.

## Reference

**`RazCryptoCheckout.open(context, options)`** returns `Future<CheckoutResult>`.

| `CheckoutOptions` | Use |
|---|---|
| `CheckoutOptions.fromCheckoutUrl(url, {locale})` | Recommended. `url` is the `checkout_url` from your server. |
| `CheckoutOptions(key:, paymentId:, {payHost, locale})` | Publishable key + payment id. `payHost` is only for staging or a self-hosted gateway. |
| `locale` | `'en'` or `'hi'`. Default: the page's own choice. |

| Result | Fields | Meaning |
|---|---|---|
| `CheckoutSuccess` | `paymentId`, `referenceId`, `status`, `signature` | Paid. Verify on your server. |
| `CheckoutPending` | `paymentId` | Seen on-chain, waiting for confirmations. |
| `CheckoutCancelled` | — | Closed without paying. |
| `CheckoutFailed` | `code`, `message` | The page could not load or the options are wrong. |

## Test it

1. Use `sk_test_…` on the server and open a payment from the app.
2. On the server run `simulate` to finish it, for example `$rc->payments()->simulate($paymentId, 'paid')` or
   `await rc.payments.simulate(paymentId, 'paid')`. The webhook arrives just like in live mode.
3. Check **Dashboard → API apps → Webhooks** for each delivery and your server's response.
4. Also test: close the checkout halfway (order stays pending), send the same webhook twice (order is fulfilled
   once), and a wrong signing secret (webhook gets `400`).

More in [Test mode](/docs/test-mode).

## Troubleshooting

| Problem | Fix |
|---|---|
| `checkout_url must be the URL returned when the payment was created` | Pass the exact `checkout_url` from the create call (it contains `?t=…`). |
| `Never use a secret key in an app` | You passed `sk_…`. Use `fromCheckoutUrl` or a `pk_…` key. |
| Blank screen in a release build | Add the `INTERNET` permission (see Android setup). |
| Wallet button does nothing on an emulator | The emulator has no MetaMask/Trust app. Test wallet links on a real phone, or pay by scanning the QR. |
| Paid on screen, order not paid | Check the webhook URL, the signing secret (test vs live) and the delivery log in the dashboard. |

## Going live

- Switch the server to `sk_live_…` and the live webhook signing secret.
- Make sure the live webhook URL is set on the live API app.
- Make one small real payment and check the order, the webhook log and your wallet.

See [Going live](/docs/going-live).
