mini-game-service 0.0.1

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

/// <https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html>
pub struct WechatLogin {
    pub app_id: String,
    pub app_secret: String,
    pub js_code: String,
}

#[derive(Debug, Deserialize)]
pub struct WechatLoginResponse {
    #[serde(default)]
    pub session_key: String,
    #[serde(default)]
    pub unionid: String,
    #[serde(default)]
    pub openid: String,
    #[serde(default)]
    pub errcode: i64,
    #[serde(default)]
    pub errmsg: String,
    // #[serde(flatten)]
    // pub other: HashMap<String, String>,
}

impl WechatLogin {
    pub async fn send(self) -> Result<WechatLoginResponse, GameError> {
        let result = reqwest::get(format!(
            "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code",
            self.app_id, self.app_secret, self.js_code
        ))
        .await?
        .json::<WechatLoginResponse>()
        .await?;
        Ok(result)
    }
}

impl WechatLoginResponse {
    pub fn as_result(self) -> Result<LoginResponse, GameError> {
        // tracing::info!("微信登录: {:#?}", result);
        if self.errcode != 0 {
            Err(GameError::service_error("Wechat", self.errmsg).with_code(self.errcode))
        }
        else {
            Ok(LoginResponse { open_id: self.openid, union_id: self.unionid, session_key: self.session_key })
        }
    }
}