rust_nicepay/services/snap/
request_access_token.rs1use crate::utils::config::Config;
2use crate::utils::helper::Helper;
3use reqwest::{Client, Error, Response};
4use serde_json::json;
5use std::future::Future;
6use std::pin::Pin;
7
8pub type MyFuture<T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send>>;
9
10pub struct AccessTokenRequester<'a> {
11 pub config: &'a Config,
12}
13
14impl<'a> AccessTokenRequester<'a> {
15 pub fn new(config: &'a Config) -> Self {
16 Self { config }
17 }
18
19 pub fn request_access_token(&self) -> MyFuture<Response> {
20 let base_url = self.config.get_snap_api_base_url();
21 let url = format!("{}/v1.0/access-token/b2b", base_url);
22
23 let x_timestamp = Helper::get_formatted_date();
24 let string_to_sign = format!("{}|{}", self.config.client_id, x_timestamp);
25 let x_signature =
26 Helper::sign_with_private_key_string(&self.config.private_key, &string_to_sign)
27 .expect("Failed to sign");
28
29 let mut headers = reqwest::header::HeaderMap::new();
30 headers.insert(
31 reqwest::header::CONTENT_TYPE,
32 "application/json".parse().unwrap(),
33 );
34 headers.insert("X-TIMESTAMP", x_timestamp.parse().unwrap());
35 headers.insert("X-CLIENT-KEY", self.config.client_id.parse().unwrap());
36 headers.insert("X-SIGNATURE", x_signature.parse().unwrap());
37
38 let body = json!({
39 "grantType": "client_credentials",
40 "additionalInfo": json!({})
41 });
42
43 let client = Client::new();
44
45 let fut = async move {
46 let response = client.post(url).headers(headers).json(&body).send().await?;
47 Ok(response)
48 };
49
50 Box::pin(fut)
51 }
52}