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
//! Client configuration: environment, credentials, timeouts, and policy knobs.

use std::fmt;
use std::time::Duration;

/// Identifies a bKash API product. Different products use different
/// subdomains and token-grant paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Product {
    /// Tokenized Checkout (`tokenized.sandbox.bka.sh`).
    Tokenized,
    /// Classic / URL-based Checkout (`checkout.sandbox.bka.sh`).
    Checkout,
    /// Authorization & Capture (lives on the `checkout` subdomain).
    AuthCapture,
    /// Subscriptions (lives on the `tokenized` subdomain).
    Subscriptions,
}

impl Product {
    /// Service subdomain for this product.
    #[must_use]
    pub fn service_subdomain(&self) -> &'static str {
        match self {
            Self::Tokenized | Self::Subscriptions => "tokenized",
            Self::Checkout | Self::AuthCapture => "checkout",
        }
    }

    /// Path component for the token-grant endpoint.
    #[must_use]
    pub fn token_path(&self) -> &'static str {
        match self {
            Self::Checkout | Self::AuthCapture => "checkout/token/grant",
            Self::Tokenized | Self::Subscriptions => "tokenized/checkout/token/grant",
        }
    }

    /// Path component for the token-refresh endpoint.
    #[must_use]
    pub fn token_refresh_path(&self) -> &'static str {
        // All products share the same refresh endpoint, hosted on the
        // tokenized subdomain.
        "tokenized/checkout/token/refresh"
    }
}

/// bKash API environment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Environment {
    /// bKash sandbox (`*.sandbox.bka.sh`).
    Sandbox,
    /// bKash production (`*.pay.bka.sh`).
    Production,
}

impl Environment {
    /// Construct a sandbox environment.
    #[must_use]
    pub fn sandbox() -> Self {
        Self::Sandbox
    }

    /// Construct a production environment.
    #[must_use]
    pub fn production() -> Self {
        Self::Production
    }

    /// Returns the full base URL (with `/v1.2.0-beta/` segment) for the given
    /// product on this environment.
    #[must_use]
    pub fn base_url(&self, product: Product) -> String {
        let host = match self {
            Self::Sandbox => "sandbox.bka.sh",
            Self::Production => "pay.bka.sh",
        };
        format!(
            "https://{}.{}/v1.2.0-beta/",
            product.service_subdomain(),
            host
        )
    }
}

/// Client configuration.
#[derive(Clone)]
pub struct Config {
    /// API environment.
    pub environment: Environment,
    /// bKash `app_key`.
    pub app_key: String,
    /// bKash `app_secret`.
    pub app_secret: String,
    /// bKash username.
    pub username: String,
    /// bKash password.
    pub password: String,
    /// Per-request HTTP timeout.
    pub timeout: Duration,
    /// Maximum number of transient retries.
    pub max_retries: u32,
    /// Optional pre-built HTTP client (for connection pooling, custom TLS,
    /// proxies). When `None`, a default client is created.
    pub http_client: Option<reqwest::Client>,
    /// Optional base URL override (for tests / wiremock).
    pub base_url: Option<String>,
}

impl Config {
    /// Construct a new [`ConfigBuilder`].
    #[must_use]
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }

    /// Construct a sandbox config builder pre-populated for the sandbox
    /// environment. Credentials must still be supplied.
    #[must_use]
    pub fn sandbox() -> ConfigBuilder {
        Self::builder().environment(Environment::Sandbox)
    }

    /// Construct a production config builder pre-populated for the
    /// production environment. Credentials must still be supplied.
    #[must_use]
    pub fn production() -> ConfigBuilder {
        Self::builder().environment(Environment::Production)
    }

    /// Validate the configuration. Returns `Err` if any required field is
    /// missing or invalid.
    pub fn validate(&self) -> Result<(), crate::Error> {
        if self.app_key.trim().is_empty() {
            return Err(crate::Error::Config("app_key is required".into()));
        }
        if self.app_secret.trim().is_empty() {
            return Err(crate::Error::Config("app_secret is required".into()));
        }
        if self.username.trim().is_empty() {
            return Err(crate::Error::Config("username is required".into()));
        }
        if self.password.trim().is_empty() {
            return Err(crate::Error::Config("password is required".into()));
        }
        if self.timeout.is_zero() {
            return Err(crate::Error::Config("timeout must be non-zero".into()));
        }
        Ok(())
    }
}

impl fmt::Debug for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Config")
            .field("environment", &self.environment)
            .field("app_key", &"***redacted***")
            .field("app_secret", &"***redacted***")
            .field("username", &"***redacted***")
            .field("password", &"***redacted***")
            .field("timeout", &self.timeout)
            .field("max_retries", &self.max_retries)
            .field(
                "http_client",
                &self.http_client.as_ref().map(|_| "<client>"),
            )
            .field("base_url", &self.base_url)
            .finish()
    }
}

/// Builder for [`Config`].
#[derive(Debug, Clone)]
pub struct ConfigBuilder {
    environment: Option<Environment>,
    app_key: Option<String>,
    app_secret: Option<String>,
    username: Option<String>,
    password: Option<String>,
    timeout: Duration,
    max_retries: u32,
    http_client: Option<reqwest::Client>,
    base_url: Option<String>,
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ConfigBuilder {
    /// Create a new builder with default timeouts / retry policy.
    #[must_use]
    pub fn new() -> Self {
        Self {
            environment: None,
            app_key: None,
            app_secret: None,
            username: None,
            password: None,
            timeout: Duration::from_secs(30),
            max_retries: 2,
            http_client: None,
            base_url: None,
        }
    }

    /// Set the environment.
    #[must_use]
    pub fn environment(mut self, env: Environment) -> Self {
        self.environment = Some(env);
        self
    }

    /// Set the `app_key`.
    #[must_use]
    pub fn app_key(mut self, key: impl Into<String>) -> Self {
        self.app_key = Some(key.into());
        self
    }

    /// Set the `app_secret`.
    #[must_use]
    pub fn app_secret(mut self, secret: impl Into<String>) -> Self {
        self.app_secret = Some(secret.into());
        self
    }

    /// Set the username.
    #[must_use]
    pub fn username(mut self, u: impl Into<String>) -> Self {
        self.username = Some(u.into());
        self
    }

    /// Set the password.
    #[must_use]
    pub fn password(mut self, p: impl Into<String>) -> Self {
        self.password = Some(p.into());
        self
    }

    /// Set the per-request timeout.
    #[must_use]
    pub fn timeout(mut self, t: Duration) -> Self {
        self.timeout = t;
        self
    }

    /// Set the maximum number of transient retries.
    #[must_use]
    pub fn max_retries(mut self, n: u32) -> Self {
        self.max_retries = n;
        self
    }

    /// Provide a pre-built HTTP client.
    #[must_use]
    pub fn http_client(mut self, c: reqwest::Client) -> Self {
        self.http_client = Some(c);
        self
    }

    /// Override the base URL (e.g. for tests pointing at wiremock).
    #[must_use]
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Build the [`Config`].
    ///
    /// Returns [`crate::Error::Config`] if any required field is missing.
    pub fn build(self) -> Result<Config, crate::Error> {
        let environment = self
            .environment
            .ok_or_else(|| crate::Error::Config("environment is required".into()))?;
        let app_key = self
            .app_key
            .ok_or_else(|| crate::Error::Config("app_key is required".into()))?;
        let app_secret = self
            .app_secret
            .ok_or_else(|| crate::Error::Config("app_secret is required".into()))?;
        let username = self
            .username
            .ok_or_else(|| crate::Error::Config("username is required".into()))?;
        let password = self
            .password
            .ok_or_else(|| crate::Error::Config("password is required".into()))?;
        let cfg = Config {
            environment,
            app_key,
            app_secret,
            username,
            password,
            timeout: self.timeout,
            max_retries: self.max_retries,
            http_client: self.http_client,
            base_url: self.base_url,
        };
        cfg.validate()?;
        Ok(cfg)
    }

    /// Validate, build the [`Config`], and immediately open a [`crate::Bkash`]
    /// client. This is the most common path:
    ///
    /// ```no_run
    /// # use bkash_rs::prelude::*;
    /// # async fn run() -> Result<(), bkash_rs::Error> {
    /// let bkash = Bkash::builder()
    ///     .environment(Environment::Sandbox)
    ///     .app_key("k").app_secret("s")
    ///     .username("u").password("p")
    ///     .build_and_connect()
    ///     .await?;
    /// # let _ = bkash;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Equivalent to `build()?.pipe(Bkash::new)`. Use [`build`](Self::build)
    /// if you want to inspect the `Config` before opening the client.
    pub async fn build_and_connect(self) -> Result<crate::Bkash, crate::Error> {
        let config = self.build()?;
        crate::Bkash::new(config).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_config() -> Config {
        Config {
            environment: Environment::Sandbox,
            app_key: "secret-app-key".into(),
            app_secret: "super-secret".into(),
            username: "secret-user".into(),
            password: "secret-pass".into(),
            timeout: Duration::from_secs(10),
            max_retries: 1,
            http_client: None,
            base_url: None,
        }
    }

    #[test]
    fn environment_base_url_tokenized_sandbox() {
        let url = Environment::Sandbox.base_url(Product::Tokenized);
        assert_eq!(url, "https://tokenized.sandbox.bka.sh/v1.2.0-beta/");
    }

    #[test]
    fn environment_base_url_tokenized_production() {
        let url = Environment::Production.base_url(Product::Tokenized);
        assert_eq!(url, "https://tokenized.pay.bka.sh/v1.2.0-beta/");
    }

    #[test]
    fn environment_base_url_checkout_sandbox() {
        let url = Environment::Sandbox.base_url(Product::Checkout);
        assert_eq!(url, "https://checkout.sandbox.bka.sh/v1.2.0-beta/");
    }

    #[test]
    fn environment_base_url_checkout_production() {
        let url = Environment::Production.base_url(Product::Checkout);
        assert_eq!(url, "https://checkout.pay.bka.sh/v1.2.0-beta/");
    }

    #[test]
    fn environment_base_url_auth_capture() {
        assert!(Environment::Sandbox
            .base_url(Product::AuthCapture)
            .starts_with("https://checkout.sandbox.bka.sh/"));
    }

    #[test]
    fn environment_base_url_subscriptions() {
        assert!(Environment::Sandbox
            .base_url(Product::Subscriptions)
            .starts_with("https://tokenized.sandbox.bka.sh/"));
    }

    #[test]
    fn config_debug_redacts_credentials() {
        let cfg = sample_config();
        let s = format!("{cfg:?}");
        assert!(!s.contains("secret-app-key"), "app_key leaked: {s}");
        assert!(!s.contains("super-secret"), "app_secret leaked: {s}");
        assert!(!s.contains("secret-user"), "username leaked: {s}");
        assert!(!s.contains("secret-pass"), "password leaked: {s}");
        assert!(
            s.contains("***redacted***"),
            "expected redaction marker: {s}"
        );
    }

    #[test]
    fn builder_validates_required_fields() {
        let r = Config::builder().build();
        assert!(r.is_err());
    }

    #[test]
    fn builder_validates_blank_credentials() {
        let r = Config::builder()
            .environment(Environment::Sandbox)
            .app_key("   ")
            .app_secret("x")
            .username("x")
            .password("x")
            .build();
        assert!(r.is_err());
    }

    #[test]
    fn builder_produces_valid_config() {
        let cfg = Config::builder()
            .environment(Environment::Sandbox)
            .app_key("k")
            .app_secret("s")
            .username("u")
            .password("p")
            .build()
            .unwrap();
        assert_eq!(cfg.environment, Environment::Sandbox);
        assert_eq!(cfg.timeout, Duration::from_secs(30));
        assert_eq!(cfg.max_retries, 2);
    }

    #[test]
    fn sandbox_and_production_helpers() {
        let cfg = Config::sandbox()
            .app_key("k")
            .app_secret("s")
            .username("u")
            .password("p")
            .build()
            .unwrap();
        assert_eq!(cfg.environment, Environment::Sandbox);
        let cfg = Config::production()
            .app_key("k")
            .app_secret("s")
            .username("u")
            .password("p")
            .build()
            .unwrap();
        assert_eq!(cfg.environment, Environment::Production);
    }

    #[test]
    fn with_base_url_overrides() {
        let cfg = Config::sandbox()
            .app_key("k")
            .app_secret("s")
            .username("u")
            .password("p")
            .with_base_url("https://example.test/")
            .build()
            .unwrap();
        assert_eq!(cfg.base_url.as_deref(), Some("https://example.test/"));
    }
}