bkash-rs 0.2.1

Idiomatic async-first Rust client for the bKash Payment Gateway API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! # bKash sandbox smoke test — staged
//!
//! Reads credentials from the environment (load via `set -a; source .env; set +a`)
//! and drives the full tokenized checkout flow in clearly-numbered stages.
//!
//! Subscription stages require the `subscriptions` feature:
//!
//! ```bash
//! cargo run --example from_env --features subscriptions -- sub-create
//! ```
//!
//! Classic (URL-based) Checkout stages require the `checkout` feature:
//!
//! ```bash
//! cargo run --example from_env --features checkout -- checkout-create
//! ```
//!
//! ## Tokenized checkout stages
//!
//! 1. `create-agreement`  -> prints `bkashURL`. Approve on your phone, then
//! 2. `execute-agreement` -> prints `agreementID`.
//! 3. `create-payment`    -> prints `bkashURL`. Approve on your phone, then
//! 4. `execute-payment`   -> prints `trxID`. From here you can also `query-payment`
//!    or `refund`.
//!
//! ## Subscription stages (same wire endpoints as tokenized agreement; the
//! `subscriptions` feature routes through the tokenized subdomain)
//!
//! 1. `sub-create`  -> prints `bkashURL`. Approve on your phone, then
//! 2. `sub-execute` -> prints `agreementID`.
//! 3. `sub-query`   -> prints current status.
//! 4. `sub-cancel`  -> prints cancelled status.
//!
//! ## Classic (URL-based) Checkout stages (requires `--features checkout`)
//!
//! One-shot URL-redirect flow — no agreement step.
//!
//! 1. `checkout-create`  -> prints `bkashURL`. Approve on your phone, then
//! 2. `checkout-execute` -> prints `trxID`.
//! 3. `checkout-query`   -> prints current status.
//! 4. `checkout-search`  -> looks up a transaction by `trxID`.
//! 5. `checkout-refund`  -> refunds a captured payment.
//! 6. `checkout-refund-status` -> queries the status of a refund.
//!
//! ## Running
//!
//! ```bash
//! set -a; source .env; set +a
//!
//! cargo run --example from_env -- create-agreement
//! # open the printed URL on your phone, approve with wallet + PIN + OTP
//!
//! cargo run --example from_env -- execute-agreement --payment-id <ID>
//! cargo run --example from_env -- create-payment --agreement-id <ID>
//! # open the printed URL on your phone, approve again
//!
//! cargo run --example from_env -- execute-payment --payment-id <ID>
//! cargo run --example from_env -- query-payment --payment-id <ID>
//! cargo run --example from_env -- refund --payment-id <ID> --trx-id <TRX> --amount 100.00
//!
//! # subscriptions (requires --features subscriptions)
//! cargo run --example from_env --features subscriptions -- sub-create
//! cargo run --example from_env --features subscriptions -- sub-execute --payment-id <ID>
//! cargo run --example from_env --features subscriptions -- sub-query   --agreement-id <ID>
//! cargo run --example from_env --features subscriptions -- sub-cancel  --agreement-id <ID>
//!
//! # classic (URL-based) checkout (requires --features checkout)
//! cargo run --example from_env --features checkout -- checkout-create
//! cargo run --example from_env --features checkout -- checkout-execute --payment-id <ID>
//! cargo run --example from_env --features checkout -- checkout-query   --payment-id <ID>
//! cargo run --example from_env --features checkout -- checkout-search  --trx-id <TRX>
//! cargo run --example from_env --features checkout -- checkout-refund  --payment-id <ID> --trx-id <TRX> --amount <BDT>
//! cargo run --example from_env --features checkout -- checkout-refund-status --payment-id <ID> --trx-id <TRX>
//! ```

use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(feature = "checkout")]
use bkash_rs::models::checkout::{
    CreatePaymentRequest as CheckoutCreatePaymentRequest, RefundRequest as CheckoutRefundRequest,
};
use bkash_rs::models::common::{Currency, Money};
use bkash_rs::models::token::GrantTokenRequest;
use bkash_rs::models::tokenized::{CreateAgreementRequest, CreatePaymentRequest, RefundRequest};
use bkash_rs::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let stage = args.first().map(String::as_str).unwrap_or("help");

    match stage {
        "create-agreement" => stage_create_agreement().await,
        "execute-agreement" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            stage_execute_agreement(&payment_id).await
        }
        "create-payment" => {
            let agreement_id = require_flag(&args, "--agreement-id")?;
            stage_create_payment(&agreement_id).await
        }
        "execute-payment" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            stage_execute_payment(&payment_id).await
        }
        "query-payment" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            stage_query_payment(&payment_id).await
        }
        "refund" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            let trx_id = require_flag(&args, "--trx-id")?;
            let amount = require_flag(&args, "--amount")?;
            stage_refund(&payment_id, &trx_id, &amount).await
        }
        "refund-status" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            let trx_id = require_flag(&args, "--trx-id")?;
            stage_refund_status(&payment_id, &trx_id).await
        }
        #[cfg(feature = "subscriptions")]
        "loop-billing" => {
            let agreement_id = require_flag(&args, "--agreement-id")?;
            let cycles: usize = optional_flag(&args, "--cycles", "2")?
                .parse()
                .map_err(|_| "invalid --cycles (expected positive integer)")?;
            let interval_secs: u64 = optional_flag(&args, "--interval-secs", "5")?
                .parse()
                .map_err(|_| "invalid --interval-secs (expected non-negative integer)")?;
            let approve_wait_secs: u64 = optional_flag(&args, "--approve-wait-secs", "20")?
                .parse()
                .map_err(|_| "invalid --approve-wait-secs (expected non-negative integer)")?;
            let amount = optional_flag(&args, "--amount", "1000.00")?;
            stage_loop_billing(
                &agreement_id,
                cycles,
                interval_secs,
                approve_wait_secs,
                &amount,
            )
            .await
        }
        #[cfg(feature = "subscriptions")]
        "sub-create" => stage_sub_create().await,
        #[cfg(feature = "subscriptions")]
        "sub-execute" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            stage_sub_execute(&payment_id).await
        }
        #[cfg(feature = "subscriptions")]
        "sub-query" => {
            let agreement_id = require_flag(&args, "--agreement-id")?;
            stage_sub_query(&agreement_id).await
        }
        #[cfg(feature = "subscriptions")]
        "sub-cancel" => {
            let agreement_id = require_flag(&args, "--agreement-id")?;
            stage_sub_cancel(&agreement_id).await
        }
        #[cfg(feature = "checkout")]
        "checkout-create" => stage_checkout_create().await,
        #[cfg(feature = "checkout")]
        "checkout-execute" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            stage_checkout_execute(&payment_id).await
        }
        #[cfg(feature = "checkout")]
        "checkout-query" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            stage_checkout_query(&payment_id).await
        }
        #[cfg(feature = "checkout")]
        "checkout-search" => {
            let trx_id = require_flag(&args, "--trx-id")?;
            stage_checkout_search(&trx_id).await
        }
        #[cfg(feature = "checkout")]
        "checkout-refund" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            let trx_id = require_flag(&args, "--trx-id")?;
            let amount = require_flag(&args, "--amount")?;
            stage_checkout_refund(&payment_id, &trx_id, &amount).await
        }
        #[cfg(feature = "checkout")]
        "checkout-refund-status" => {
            let payment_id = require_flag(&args, "--payment-id")?;
            let trx_id = require_flag(&args, "--trx-id")?;
            stage_checkout_refund_status(&payment_id, &trx_id).await
        }
        _ => {
            print_help();
            Ok(())
        }
    }
}

fn print_help() {
    println!(
        "bKash sandbox smoke test — staged\n\n\
         Tokenized checkout:\n  \
           create-agreement\n  \
           execute-agreement  --payment-id <ID>\n  \
           create-payment     --agreement-id <ID>\n  \
           execute-payment    --payment-id <ID>\n  \
           query-payment      --payment-id <ID>\n  \
           refund             --payment-id <ID> --trx-id <TRX> --amount <BDT>\n  \
           refund-status      --payment-id <ID> --trx-id <TRX>\n\n\
         Subscriptions:\n  \
           sub-create\n  \
           sub-execute        --payment-id <ID>\n  \
           sub-query          --agreement-id <ID>\n  \
           sub-cancel         --agreement-id <ID>\n\n\
         Classic (URL-based) Checkout:\n  \
           checkout-create\n  \
           checkout-execute   --payment-id <ID>\n  \
           checkout-query     --payment-id <ID>\n  \
           checkout-search    --trx-id <TRX>\n  \
           checkout-refund    --payment-id <ID> --trx-id <TRX> --amount <BDT>\n  \
           checkout-refund-status --payment-id <ID> --trx-id <TRX>\n\n\
         Recurring billing loop:\n  \
           loop-billing       --agreement-id <ID>\n                           [--cycles N=2]\n\
                               [--interval-secs S=5]\n\
                               [--approve-wait-secs A=20]\n\
                               [--amount BDT=1000.00]\n\
         Drives N create_payment -> wait A seconds for wallet approval ->\n\
         execute_payment cycles, sleeping S seconds between cycles.\n\
         KNOWN LIMITATION: bKash's sandbox execute_payment locks each\n\
         paymentID on the first call (2056 if not approved, 2117 forever\n\
         after). No retry path. This loop is best-effort and is NOT a\n\
         production-ready recurring-billing solution. For real billing,\n\
         register a bKash webhook for wallet-side completion signals.\n"
    );
}

fn require_flag(args: &[String], flag: &str) -> Result<String, Box<dyn std::error::Error>> {
    let i = args
        .iter()
        .position(|a| a == flag)
        .ok_or_else(|| format!("missing flag: {flag}"))?;
    args.get(i + 1)
        .cloned()
        .ok_or_else(|| format!("flag {flag} has no value").into())
}

#[cfg_attr(not(feature = "subscriptions"), allow(dead_code))]
fn optional_flag(
    args: &[String],
    flag: &str,
    default: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    match args.iter().position(|a| a == flag) {
        Some(i) => args
            .get(i + 1)
            .cloned()
            .ok_or_else(|| format!("flag {flag} has no value").into()),
        None => Ok(default.to_string()),
    }
}

// -- Shared client construction ------------------------------------------

struct Ctx {
    bkash: Bkash,
    app_key: String,
    callback_url: String,
    payer_reference: String,
    amount_str: String,
}

async fn build_ctx() -> Result<Ctx, Box<dyn std::error::Error>> {
    let app_key = std::env::var("BKASH_APP_KEY")?;
    let app_secret = std::env::var("BKASH_APP_SECRET")?;
    let username = std::env::var("BKASH_USERNAME")?;
    let password = std::env::var("BKASH_PASSWORD")?;

    let environment = match std::env::var("BKASH_ENVIRONMENT")
        .unwrap_or_else(|_| "sandbox".to_string())
        .to_lowercase()
        .as_str()
    {
        "production" | "prod" => Environment::Production,
        _ => Environment::Sandbox,
    };

    let callback_url = std::env::var("BKASH_CALLBACK_URL")
        .unwrap_or_else(|_| "https://merchant.test/callback".to_string());
    let payer_reference =
        std::env::var("BKASH_PAYER_REFERENCE").unwrap_or_else(|_| "demo-payer-001".to_string());
    let amount_str = std::env::var("BKASH_AMOUNT").unwrap_or_else(|_| "100.00".to_string());

    println!(
        "== bKash {} ==",
        if matches!(environment, Environment::Production) {
            "production"
        } else {
            "sandbox"
        }
    );
    println!("username    : {username}");
    println!("amount      : {amount_str} BDT");
    println!();

    let bkash = Bkash::builder()
        .environment(environment)
        .app_key(&app_key)
        .app_secret(&app_secret)
        .username(&username)
        .password(&password)
        .build_and_connect()
        .await?;
    // Smoke-grant so we fail fast if credentials are wrong.
    let _ = bkash
        .tokenized()
        .grant_token(GrantTokenRequest::new(&app_key, &app_secret))
        .await?;

    Ok(Ctx {
        bkash,
        app_key,
        callback_url,
        payer_reference,
        amount_str,
    })
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

// -- Stage 1: create_agreement ------------------------------------------

async fn stage_create_agreement() -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[1/4 create-agreement]");

    let req = CreateAgreementRequest::new(
        ctx.payer_reference.clone(),
        ctx.callback_url.clone(),
        Money::bdt(&ctx.amount_str),
        Currency::Bdt,
    )
    .with_merchant_invoice_number(format!("AGR-{}", now_secs()));

    let resp = ctx.bkash.tokenized().create_agreement(req).await?;
    println!("  paymentID : {}", resp.payment_id);
    println!("  bkashURL  : {}", resp.bkash_url);
    println!();
    println!(">>> Open the bkashURL above on your phone.");
    println!(">>> Approve with wallet 01770618575, PIN 12121, OTP 123456.");
    println!(
        ">>> Then run:\n    cargo run --example from_env -- execute-agreement --payment-id {}",
        resp.payment_id
    );
    Ok(())
}

// -- Stage 2: execute_agreement ------------------------------------------

async fn stage_execute_agreement(payment_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[2/4 execute-agreement] paymentID={payment_id}");

    let resp = ctx.bkash.tokenized().execute_agreement(payment_id).await?;
    println!("  agreementID : {}", resp.agreement_id);
    println!("  payerReference : {}", resp.payer_reference);
    println!();
    println!(
        ">>> Next: cargo run --example from_env -- create-payment --agreement-id {}",
        resp.agreement_id
    );
    // Keep app_key alive so the env-var requirement stays visible if someone
    // refactors the example.
    let _ = ctx.app_key;
    Ok(())
}

// -- Stage 3: create_payment ---------------------------------------------

async fn stage_create_payment(agreement_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[3a/4 create-payment] agreementID={agreement_id}");

    let amount = Money::bdt(&ctx.amount_str);
    let req = CreatePaymentRequest::new(
        agreement_id,
        ctx.payer_reference.clone(),
        ctx.callback_url.clone(),
        amount,
        Currency::Bdt,
    )
    .with_merchant_invoice_number(format!("PAY-{}", now_secs()));

    let resp = ctx.bkash.tokenized().create_payment(req).await?;
    println!("  paymentID : {}", resp.payment_id);
    println!("  bkashURL  : {}", resp.bkash_url);
    println!();
    println!(">>> Open the bkashURL above on your phone.");
    println!(">>> Approve with wallet 01770618575, PIN 12121, OTP 123456.");
    println!(
        ">>> Then run:\n    cargo run --example from_env -- execute-payment --payment-id {}",
        resp.payment_id
    );
    Ok(())
}

// -- Stage 4: execute_payment --------------------------------------------

async fn stage_execute_payment(payment_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[3b/4 execute-payment] paymentID={payment_id}");

    let resp = ctx.bkash.tokenized().execute_payment(payment_id).await?;
    println!("  trxID      : {}", resp.trx_id);
    println!("  trxStatus  : {}", resp.transaction_status);
    println!();
    println!(">>> Next: cargo run --example from_env -- query-payment --payment-id {payment_id}");
    println!(
        ">>> Or:    cargo run --example from_env -- refund --payment-id {payment_id} --trx-id {} --amount {}",
        resp.trx_id, ctx.amount_str
    );
    Ok(())
}

// -- Stage 5: query_payment ----------------------------------------------

async fn stage_query_payment(payment_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[query-payment] paymentID={payment_id}");

    let resp = ctx.bkash.tokenized().query_payment(payment_id).await?;
    println!("  trxID      : {}", resp.trx_id);
    println!("  trxStatus  : {}", resp.transaction_status);
    println!("  amount     : {:?}", resp.amount);
    println!("  currency   : {:?}", resp.currency);
    Ok(())
}

// -- Stage 6: refund -----------------------------------------------------

async fn stage_refund(
    payment_id: &str,
    trx_id: &str,
    amount: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[refund] paymentID={payment_id} trxID={trx_id} amount={amount}");

    let req = RefundRequest::new(
        payment_id,
        trx_id,
        Money::bdt(amount),
        format!("SKU-{}", now_secs()),
        "Sandbox smoke test refund",
    );
    let resp = ctx.bkash.tokenized().refund(req).await?;
    println!("  originalTrxID : {}", resp.trx_id);
    println!("  refundTrxID   : {}", resp.refund_trx_id);
    println!("  refundAmount  : {:?}", resp.refund_amount);
    Ok(())
}

// -- Stage 7: refund_status ----------------------------------------------

async fn stage_refund_status(
    payment_id: &str,
    trx_id: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[refund-status] paymentID={payment_id} trxID={trx_id}");

    let resp = ctx
        .bkash
        .tokenized()
        .refund_status(payment_id, trx_id)
        .await?;
    println!("  status : {:?}", resp);
    Ok(())
}

// -- Subscription stages -------------------------------------------------
//
// Subscriptions use the same wire endpoints as the tokenized agreement flow
// (POST /tokenized/checkout/create, /execute, /agreement/status, /agreement/cancel)
// but are routed through the `Subscriptions` product so they appear under
// the merchant's recurring-billing dashboard. The request/response models
// are identical to the tokenized agreement types.

#[cfg(feature = "subscriptions")]
async fn stage_sub_create() -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[sub-create]");

    let req = CreateAgreementRequest::new(
        ctx.payer_reference.clone(),
        ctx.callback_url.clone(),
        Money::bdt(&ctx.amount_str),
        Currency::Bdt,
    )
    .with_merchant_invoice_number(format!("SUB-{}", now_secs()));

    let resp = ctx.bkash.subscriptions().create_subscription(req).await?;
    println!("  paymentID : {}", resp.payment_id);
    println!("  bkashURL  : {}", resp.bkash_url);
    println!();
    println!(">>> Open the bkashURL above on your phone.");
    println!(">>> Approve with wallet 01770618575, PIN 12121, OTP 123456.");
    println!(
        ">>> Then run:\n    cargo run --example from_env -- sub-execute --payment-id {}",
        resp.payment_id
    );
    Ok(())
}

#[cfg(feature = "subscriptions")]
async fn stage_sub_execute(payment_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[sub-execute] paymentID={payment_id}");

    let resp = ctx
        .bkash
        .subscriptions()
        .execute_subscription(payment_id)
        .await?;
    println!("  agreementID     : {}", resp.agreement_id);
    println!("  agreementStatus : {}", resp.agreement_status);
    println!("  payerReference  : {}", resp.payer_reference);
    println!();
    println!(
        ">>> Next: cargo run --example from_env -- sub-query --agreement-id {}",
        resp.agreement_id
    );
    println!(
        ">>> Or:    cargo run --example from_env -- sub-cancel --agreement-id {}",
        resp.agreement_id
    );
    Ok(())
}

#[cfg(feature = "subscriptions")]
async fn stage_sub_query(agreement_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[sub-query] agreementID={agreement_id}");

    let resp = ctx
        .bkash
        .subscriptions()
        .query_subscription(agreement_id)
        .await?;
    println!("  agreementID       : {}", resp.agreement_id);
    println!("  agreementStatus   : {}", resp.agreement_status);
    println!("  amount            : {:?}", resp.amount);
    println!("  currency          : {:?}", resp.currency);
    println!("  payerReference    : {}", resp.payer_reference);
    println!("  customerMsisdn    : {}", resp.customer_msisdn);
    Ok(())
}

#[cfg(feature = "subscriptions")]
async fn stage_sub_cancel(agreement_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[sub-cancel] agreementID={agreement_id}");

    let resp = ctx
        .bkash
        .subscriptions()
        .cancel_subscription(agreement_id)
        .await?;
    println!("  agreementID     : {}", resp.agreement_id);
    println!("  agreementStatus : {}", resp.agreement_status);
    Ok(())
}

// -- Recurring billing loop ---------------------------------------------
//
// Drives N cycles of `create_payment` -> wait `--approve-wait-secs` for
// wallet approval -> `execute_payment` against an existing subscription
// `agreementID`. Between cycles the program sleeps for `--interval-secs`
// (default 5s) so that the caller can simulate a monthly cadence without
// waiting a real month.
//
// IMPORTANT: bKash locks each paymentID on the first `execute_payment`
// call. If you call too early (customer hasn't approved yet) the server
// returns 2056 Invalid Payment State and the payment is dead — every
// subsequent call returns 2117. So the operator MUST approve on the
// wallet within `--approve-wait-secs` seconds of seeing the bkashURL.

#[cfg(feature = "subscriptions")]
async fn stage_loop_billing(
    agreement_id: &str,
    cycles: usize,
    interval_secs: u64,
    approve_wait_secs: u64,
    amount: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    if cycles == 0 {
        return Err("--cycles must be at least 1".into());
    }
    let ctx = build_ctx().await?;
    println!("[loop-billing]");
    println!("  agreementID : {agreement_id}");
    println!("  cycles      : {cycles}");
    println!("  amount/cycle: {amount} BDT");
    println!("  interval    : {interval_secs}s between cycles");
    println!();
    println!("NOTE: each cycle pauses for you to approve a bkashURL on your phone.");
    println!("      Use --interval-secs 2592000 to simulate a real monthly cadence.");
    println!();

    let money = Money::bdt(amount);
    let mut completed: Vec<(usize, String, String)> = Vec::new(); // (cycle, trxID, paymentID)

    for cycle in 1..=cycles {
        println!("=== Cycle {cycle}/{cycles} ===");

        // 1) Create the payment against the agreement
        let create_req = CreatePaymentRequest::new(
            agreement_id,
            ctx.payer_reference.clone(),
            ctx.callback_url.clone(),
            money.clone(),
            Currency::Bdt,
        )
        .with_merchant_invoice_number(format!("BILL-{cycle}-{}", now_secs()));

        let created = ctx.bkash.tokenized().create_payment(create_req).await?;
        println!("  paymentID : {}", created.payment_id);
        println!("  bkashURL  : {}", created.bkash_url);
        println!();
        println!(">>> Approve the bkashURL above on your phone");
        println!(">>> (wallet 01770618575, PIN 12121, OTP 123456)");

        // Wait -- interval_secs seconds for the operator to approve on the
        // wallet before we call execute_payment. This is a poor man's
        // replacement for a webhook. The interval needs to be tuned:
        // too short and you haven't approved yet (2056), too long and
        // the test runs slowly. Use `--approve-wait-secs 30` if you need
        // more time.
        if approve_wait_secs > 0 {
            println!(">>> waiting {approve_wait_secs}s for wallet approval...");
            tokio::time::sleep(std::time::Duration::from_secs(approve_wait_secs)).await;
        }

        // 2) Execute the payment — single shot. bKash locks the payment on
        // first call: too early returns 2056, after that 2117 forever.
        let executed = ctx
            .bkash
            .tokenized()
            .execute_payment(&created.payment_id)
            .await?;
        println!(
            "  -> cycle {cycle} charged: trxID = {}, trxStatus = {}, amount = {}",
            executed.trx_id, executed.transaction_status, executed.amount
        );
        completed.push((cycle, executed.trx_id.clone(), created.payment_id.clone()));

        if cycle < cycles && interval_secs > 0 {
            println!(
                "  sleeping {interval_secs}s before next cycle (simulating next billing period)..."
            );
            tokio::time::sleep(std::time::Duration::from_secs(interval_secs)).await;
        }
        println!();
    }

    println!("=== Summary ===");
    println!("  agreementID: {agreement_id}");
    println!("  cycles     : {cycles}");
    println!("  amount/cyc : {amount} BDT");
    let amount_num: u64 = amount
        .split('.')
        .next()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);
    println!(
        "  total      : {} BDT (estimate)",
        cycles as u64 * amount_num
    );
    println!();
    println!("  {:>4}  {:<22}  paymentID", "cyc", "trxID");
    for (cycle, trx_id, payment_id) in &completed {
        println!("  {cycle:>4}  {trx_id:<22}  {payment_id}");
    }
    Ok(())
}

// -- Classic (URL-based) Checkout stages -------------------------------
//
// The classic product uses the `checkout` subdomain with its own token
// (`POST /checkout/token/grant`) and the `mode = "0011"` create-payment
// payload. There is no agreement step — it's a one-shot URL-redirect
// flow identical in shape to the tokenized product but routed through
// `bkash.checkout()` instead of `bkash.tokenized()`.

#[cfg(feature = "checkout")]
async fn stage_checkout_create() -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[checkout-create]");

    let req = CheckoutCreatePaymentRequest::new(
        ctx.payer_reference.clone(),
        ctx.callback_url.clone(),
        Money::bdt(&ctx.amount_str),
        Currency::Bdt,
    )
    .with_merchant_invoice_number(format!("CHK-{}", now_secs()));

    let resp = ctx.bkash.checkout().create_payment(req).await?;
    println!("  paymentID : {}", resp.payment_id);
    println!("  bkashURL  : {}", resp.bkash_url);
    println!();
    println!(">>> Open the bkashURL above on your phone.");
    println!(">>> Approve with wallet 01770618575, PIN 12121, OTP 123456.");
    println!(
        ">>> Then run:\n    cargo run --example from_env --features checkout -- checkout-execute --payment-id {}",
        resp.payment_id
    );
    Ok(())
}

#[cfg(feature = "checkout")]
async fn stage_checkout_execute(payment_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[checkout-execute] paymentID={payment_id}");

    let resp = ctx.bkash.checkout().execute_payment(payment_id).await?;
    println!("  paymentID : {}", resp.payment_id);
    println!("  trxID     : {}", resp.trx_id);
    println!("  trxStatus : {}", resp.transaction_status);
    println!("  amount    : {:?}", resp.amount);
    println!();
    println!(
        ">>> Next: cargo run --example from_env --features checkout -- checkout-query --payment-id {payment_id}"
    );
    println!(
        ">>> Or:    cargo run --example from_env --features checkout -- checkout-refund --payment-id {payment_id} --trx-id {} --amount {}",
        resp.trx_id, ctx.amount_str
    );
    Ok(())
}

#[cfg(feature = "checkout")]
async fn stage_checkout_query(payment_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[checkout-query] paymentID={payment_id}");

    let resp = ctx.bkash.checkout().query_payment(payment_id).await?;
    println!("  paymentID : {}", resp.payment_id);
    println!("  trxID     : {}", resp.trx_id);
    println!("  trxStatus : {}", resp.transaction_status);
    println!("  amount    : {:?}", resp.amount);
    println!("  currency  : {:?}", resp.currency);
    Ok(())
}

#[cfg(feature = "checkout")]
async fn stage_checkout_search(trx_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[checkout-search] trxID={trx_id}");

    let resp = ctx.bkash.checkout().search_transaction(trx_id).await?;
    println!("  trxID            : {}", resp.trx_id);
    println!("  trxStatus        : {}", resp.transaction_status);
    println!("  amount           : {:?}", resp.amount);
    println!("  saleAmount       : {:?}", resp.sale_amount);
    println!("  customerMsisdn   : {}", resp.customer_msisdn);
    println!("  isCoupon         : {}", resp.is_coupon());
    Ok(())
}

#[cfg(feature = "checkout")]
async fn stage_checkout_refund(
    payment_id: &str,
    trx_id: &str,
    amount: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[checkout-refund] paymentID={payment_id} trxID={trx_id} amount={amount}");

    let req = CheckoutRefundRequest::new(
        payment_id,
        trx_id,
        Money::bdt(amount),
        format!("SKU-{}", now_secs()),
        "Sandbox smoke test refund (classic)",
    );
    let resp = ctx.bkash.checkout().refund(req).await?;
    println!("  originalTrxID : {}", resp.trx_id);
    println!("  refundTrxID   : {}", resp.refund_trx_id);
    println!("  refundAmount  : {:?}", resp.refund_amount);
    Ok(())
}

#[cfg(feature = "checkout")]
async fn stage_checkout_refund_status(
    payment_id: &str,
    trx_id: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let ctx = build_ctx().await?;
    println!("[checkout-refund-status] paymentID={payment_id} trxID={trx_id}");

    let resp = ctx
        .bkash
        .checkout()
        .refund_status(payment_id, trx_id)
        .await?;
    println!("  refundTrxID : {}", resp.refund_trx_id);
    println!("  status      : {:?}", resp);
    Ok(())
}