mini-game-service 0.0.1

提供小游戏后端服务
Documentation
use super::*;

/// <https://ks-game-docs.kuaishou.com/minigame/api/open/login/auth.code2Session.html>
pub struct KuaiShouLogin {
    pub app_id: String,
    pub app_secret: String,
    pub js_code: String,
}

#[derive(Debug, Deserialize)]
pub struct KuaiShouLoginResponse {
    #[serde(default)]
    pub result: i64,
    #[serde(default)]
    pub error_msg: String,
    #[serde(default)]
    pub open_id: String,
    #[serde(default)]
    pub session_key: String,
    #[serde(default)]
    pub union_id: String,
    // #[serde(flatten)]
    // pub other: HashMap<String, String>,
}

impl KuaiShouLogin {
    pub fn new(app_id: String, app_secret: String, js_code: String) -> KuaiShouLogin {
        KuaiShouLogin { app_id, app_secret, js_code }
    }
    pub async fn send(self) -> Result<KuaiShouLoginResponse, GameError> {
        let result = reqwest::get(format!("https://open.kuaishou.com/game/minigame/jscode2session?app_id={}&app_secret={}&js_code={}&grant_type=authorization_code", self.app_id, self.app_secret,self.js_code)).await?
            .json::<KuaiShouLoginResponse>().await?
            ;
        Ok(result)
    }
}

impl KuaiShouLoginResponse {
    pub fn as_result(self) -> Result<LoginResponse, GameError> {
        if self.result != 1 {
            Err(GameError::service_error("KuaiShou", self.error_msg).with_code(self.result))
        }
        else {
            Ok(LoginResponse { open_id: self.open_id, union_id: self.union_id, session_key: self.session_key })
        }
    }
}