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
//! Tokenized Checkout: Payment request and response types.
//!
//! The flow for executing a tokenized payment is:
//!
//! 1. [`CreatePaymentRequest`] (`mode = "0001"`, with `agreementID`) →
//!    [`CreatePaymentResponse`] returns a `paymentID`.
//! 2. Customer completes wallet approval.
//! 3. [`ExecutePaymentRequest`] → [`ExecutePaymentResponse`] to capture the
//!    final state.
//! 4. [`QueryPaymentRequest`] → [`QueryPaymentResponse`] for the current
//!    status.

use serde::{Deserialize, Serialize};

use crate::models::common::{Currency, Intent, Money};

/// `mode` discriminator value for `POST /tokenized/checkout/create` when
/// creating a **payment against an existing agreement**.
pub const PAYMENT_MODE: &str = "0001";

/// Request body for creating a tokenized checkout payment (against an
/// existing agreement).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CreatePaymentRequest {
    /// Discriminator. Always [`PAYMENT_MODE`] (`"0001"`).
    #[serde(rename = "mode")]
    pub mode: String,

    /// Agreement ID against which this payment is being made.
    #[serde(rename = "agreementID")]
    pub agreement_id: String,

    /// Merchant's reference for the payer (e.g. internal customer ID).
    #[serde(rename = "payerReference")]
    pub payer_reference: String,

    /// URL bKash redirects to once the customer has completed the
    /// wallet-side flow.
    #[serde(rename = "callbackURL")]
    pub callback_url: String,

    /// Payment amount.
    pub amount: Money,

    /// Currency. bKash currently only supports BDT.
    pub currency: Currency,

    /// Intent. Typically [`Intent::Sale`].
    pub intent: Intent,

    /// Optional merchant invoice number.
    #[serde(
        rename = "merchantInvoiceNumber",
        skip_serializing_if = "Option::is_none"
    )]
    pub merchant_invoice_number: Option<String>,

    /// Optional merchant association info in TLV format. The bKash TLV
    /// format is `tag1value1tag2value2...`, where each tag is a 4-byte ASCII
    /// string and each value is a UTF-8 string.
    #[serde(
        rename = "merchantAssociationInfo",
        skip_serializing_if = "Option::is_none"
    )]
    pub merchant_association_info: Option<String>,
}

impl CreatePaymentRequest {
    /// Construct a new create-payment request with sensible defaults.
    ///
    /// `mode` is automatically set to [`PAYMENT_MODE`] (`"0001"`) and
    /// `intent` defaults to [`Intent::Sale`].
    #[must_use]
    pub fn new(
        agreement_id: impl Into<String>,
        payer_reference: impl Into<String>,
        callback_url: impl Into<String>,
        amount: Money,
        currency: Currency,
    ) -> Self {
        Self {
            mode: PAYMENT_MODE.to_string(),
            agreement_id: agreement_id.into(),
            payer_reference: payer_reference.into(),
            callback_url: callback_url.into(),
            amount,
            currency,
            intent: Intent::Sale,
            merchant_invoice_number: None,
            merchant_association_info: None,
        }
    }

    /// Override the merchant invoice number.
    #[must_use]
    pub fn with_merchant_invoice_number(mut self, n: impl Into<String>) -> Self {
        self.merchant_invoice_number = Some(n.into());
        self
    }

    /// Attach TLV-formatted merchant association info.
    #[must_use]
    pub fn with_merchant_association_info(mut self, tlv: impl Into<String>) -> Self {
        self.merchant_association_info = Some(tlv.into());
        self
    }
}

/// Response from creating a payment. Contains the `paymentID` that the
/// client passes to [`execute_payment`](super::super::super::tokenized::TokenizedCheckoutClient::execute_payment).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CreatePaymentResponse {
    /// `paymentID` to be passed to the execute step.
    #[serde(rename = "paymentID")]
    pub payment_id: String,

    /// bKash-generated URL for the customer's wallet-side approval.
    #[serde(rename = "bkashURL", default)]
    pub bkash_url: String,

    /// Echoed callback URL.
    #[serde(rename = "callbackURL", default)]
    pub callback_url: String,

    /// Payment creation timestamp (ISO-8601).
    #[serde(rename = "paymentCreateTime", default)]
    pub payment_create_time: String,

    /// Agreement ID this payment was made against.
    #[serde(rename = "agreementID", default)]
    pub agreement_id: String,

    /// Echoed `payerReference`.
    #[serde(rename = "payerReference", default)]
    pub payer_reference: String,

    /// Echoed organization short code.
    #[serde(rename = "orgShortCode", default)]
    pub org_short_code: String,

    /// Echoed currency.
    #[serde(default)]
    pub currency: Currency,

    /// Echoed intent.
    #[serde(default)]
    pub intent: Intent,

    /// Echoed merchant invoice number.
    #[serde(rename = "merchantInvoiceNumber", default)]
    pub merchant_invoice_number: String,
}

/// Request body for executing a payment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExecutePaymentRequest {
    /// `paymentID` returned by [`CreatePaymentResponse::payment_id`].
    #[serde(rename = "paymentID")]
    pub payment_id: String,
}

impl ExecutePaymentRequest {
    /// Construct a new execute-payment request.
    #[must_use]
    pub fn new(payment_id: impl Into<String>) -> Self {
        Self {
            payment_id: payment_id.into(),
        }
    }
}

/// Response from executing a payment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExecutePaymentResponse {
    /// `paymentID` that was executed.
    #[serde(rename = "paymentID")]
    pub payment_id: String,

    /// bKash transaction ID (`trxID`).
    #[serde(rename = "trxID", default)]
    pub trx_id: String,

    /// Customer MSISDN that completed the payment.
    #[serde(rename = "customerMsisdn", default)]
    pub customer_msisdn: String,

    /// Echoed `payerReference`.
    #[serde(rename = "payerReference", default)]
    pub payer_reference: String,

    /// Echoed agreement ID.
    #[serde(rename = "agreementID", default)]
    pub agreement_id: String,

    /// Organization short code.
    #[serde(rename = "orgShortCode", default)]
    pub org_short_code: String,

    /// Echoed merchant invoice number.
    #[serde(rename = "merchantInvoiceNumber", default)]
    pub merchant_invoice_number: String,

    /// Payment execution timestamp (ISO-8601).
    #[serde(rename = "paymentExecuteTime", default)]
    pub payment_execute_time: String,

    /// Echoed currency.
    #[serde(default)]
    pub currency: Currency,

    /// Echoed intent.
    #[serde(default)]
    pub intent: Intent,

    /// Final transaction status (e.g. `"Completed"`).
    #[serde(rename = "transactionStatus", default)]
    pub transaction_status: String,

    /// Final amount charged.
    #[serde(default)]
    pub amount: Money,
}

/// Request body for querying a payment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct QueryPaymentRequest {
    /// `paymentID` to query.
    #[serde(rename = "paymentID")]
    pub payment_id: String,
}

impl QueryPaymentRequest {
    /// Construct a new query-payment request.
    #[must_use]
    pub fn new(payment_id: impl Into<String>) -> Self {
        Self {
            payment_id: payment_id.into(),
        }
    }
}

/// Response from querying a payment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct QueryPaymentResponse {
    /// `paymentID` queried.
    #[serde(rename = "paymentID")]
    pub payment_id: String,

    /// bKash transaction ID.
    #[serde(rename = "trxID", default)]
    pub trx_id: String,

    /// Customer MSISDN.
    #[serde(rename = "customerMsisdn", default)]
    pub customer_msisdn: String,

    /// Echoed `payerReference`.
    #[serde(rename = "payerReference", default)]
    pub payer_reference: String,

    /// Echoed agreement ID.
    #[serde(rename = "agreementID", default)]
    pub agreement_id: String,

    /// Echoed organization short code.
    #[serde(rename = "orgShortCode", default)]
    pub org_short_code: String,

    /// Echoed merchant invoice number.
    #[serde(rename = "merchantInvoiceNumber", default)]
    pub merchant_invoice_number: String,

    /// Echoed callback URL.
    #[serde(rename = "callbackURL", default)]
    pub callback_url: String,

    /// Echoed currency.
    #[serde(default)]
    pub currency: Currency,

    /// Echoed intent.
    #[serde(default)]
    pub intent: Intent,

    /// Echoed amount.
    #[serde(default)]
    pub amount: Money,

    /// Final transaction status (e.g. `"Completed"`).
    #[serde(rename = "transactionStatus", default)]
    pub transaction_status: String,

    /// Timestamp the payment was executed (ISO-8601).
    #[serde(rename = "paymentExecuteTime", default)]
    pub payment_execute_time: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::common::Currency;

    #[test]
    fn create_payment_serialises_with_mode_0001_and_intent_sale() {
        let req = CreatePaymentRequest::new(
            "AG0001",
            "cust-1",
            "https://example.test/cb",
            Money::bdt("50.00"),
            Currency::Bdt,
        );
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["mode"], "0001");
        assert_eq!(json["agreementID"], "AG0001");
        assert_eq!(json["intent"], "sale");
        assert_eq!(json["payerReference"], "cust-1");
        assert_eq!(json["amount"], "50.00");
        assert_eq!(json["currency"], "BDT");
        assert!(json.get("merchantInvoiceNumber").is_none());
        assert!(json.get("merchantAssociationInfo").is_none());
    }

    #[test]
    fn create_payment_with_tlv_serialises() {
        let req = CreatePaymentRequest::new(
            "AG0001",
            "cust-1",
            "https://example.test/cb",
            Money::bdt("50.00"),
            Currency::Bdt,
        )
        .with_merchant_invoice_number("INV-2")
        .with_merchant_association_info("tag1value1");
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["merchantInvoiceNumber"], "INV-2");
        assert_eq!(json["merchantAssociationInfo"], "tag1value1");
    }

    #[test]
    fn execute_payment_request_serialises() {
        let req = ExecutePaymentRequest::new("TR0001");
        let json: serde_json::Value = serde_json::to_value(&req).unwrap();
        assert_eq!(json["paymentID"], "TR0001");
    }

    #[test]
    fn execute_payment_response_parses_minimal() {
        let body = r#"{
            "paymentID": "TR0001",
            "trxID": "8A00ABCD",
            "transactionStatus": "Completed",
            "amount": "50.00",
            "currency": "BDT",
            "intent": "sale",
            "paymentExecuteTime": "2026-06-22T10:00:00:000 GMT+06:00"
        }"#;
        let resp: ExecutePaymentResponse = serde_json::from_str(body).unwrap();
        assert_eq!(resp.payment_id, "TR0001");
        assert_eq!(resp.trx_id, "8A00ABCD");
        assert_eq!(resp.transaction_status, "Completed");
        assert_eq!(resp.amount.as_str(), "50.00");
    }

    // ---- proptest round-trips -----------------------------------------

    use proptest::prelude::*;

    // `CreatePaymentRequest` is a struct of plain `String` fields plus a
    // `Money` (which is itself a string newtype). Generating arbitrary
    // `String` values and comparing via serialised JSON is the simplest
    // way to assert that all `serde` attributes are mutually consistent.
    proptest! {
        #[test]
        fn create_payment_request_roundtrip(
            agreement_id in ".*",
            payer_ref in ".*",
            callback in ".*",
            amount in ".*",
            intent in proptest::sample::select(vec![Intent::Sale, Intent::Authorization]),
        ) {
            let req = CreatePaymentRequest {
                mode: PAYMENT_MODE.to_string(),
                agreement_id,
                payer_reference: payer_ref,
                callback_url: callback,
                amount: Money::new(amount),
                currency: Currency::Bdt,
                intent,
                merchant_invoice_number: None,
                merchant_association_info: None,
            };
            let json = serde_json::to_string(&req).unwrap();
            let back: CreatePaymentRequest = serde_json::from_str(&json).unwrap();
            let json2 = serde_json::to_string(&back).unwrap();
            prop_assert_eq!(json, json2);
        }

        #[test]
        fn create_payment_request_roundtrip_with_optional_fields(
            inv in ".*",
            tlv in ".*",
        ) {
            let req = CreatePaymentRequest::new(
                "AG-1",
                "cust-1",
                "https://example.test/cb",
                Money::bdt("1.00"),
                Currency::Bdt,
            )
            .with_merchant_invoice_number(inv)
            .with_merchant_association_info(tlv);
            let json = serde_json::to_string(&req).unwrap();
            let back: CreatePaymentRequest = serde_json::from_str(&json).unwrap();
            prop_assert_eq!(
                back.merchant_invoice_number,
                req.merchant_invoice_number
            );
            prop_assert_eq!(
                back.merchant_association_info,
                req.merchant_association_info
            );
        }
    }
}