battle_net_oauth/
lib.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Deserialize, Serialize)]
4pub struct OAuthToken {
5    pub access_token: String,
6    pub token_type: String,
7    pub expires_in: usize,
8}
9
10/// To retrieve a token, you need to provide your client_id and client_secret as well as a region (US, EU, APAC or CN)
11///
12/// ```rust
13/// let token = battle_net_oauth::get_oauth_token("client_id", "client_secret", "region");
14/// ```
15pub async fn get_oauth_token(
16    client_id: &str,
17    client_secret: &str,
18    region: &str,
19) -> Result<OAuthToken, Box<dyn std::error::Error + Send + Sync>> {
20    let client = reqwest::Client::new();
21    let url = if region.to_lowercase() == "cn" {
22        "https://www.battlenet.com.cn/oauth/token".to_string()
23    } else {
24        format!("https://{}.battle.net/oauth/token", region.to_lowercase())
25    };
26
27    let resp: OAuthToken = client
28        .post(&url)
29        .basic_auth(client_id, Some(client_secret))
30        .form(&[("grant_type", "client_credentials")])
31        .send()
32        .await?
33        .json()
34        .await?;
35
36    Ok(resp)
37}