Skip to main content

wechat_mp_sdk/api/
face.rs

1//! Face Verification API
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9use super::{WechatApi, WechatContext};
10use crate::error::WechatError;
11
12#[non_exhaustive]
13#[derive(Debug, Clone, Serialize)]
14pub struct GetVerifyIdRequest {
15    #[serde(flatten)]
16    pub payload: HashMap<String, Value>,
17}
18
19#[non_exhaustive]
20#[derive(Debug, Clone, Serialize)]
21pub struct QueryVerifyInfoRequest {
22    pub verify_token: String,
23}
24
25#[non_exhaustive]
26#[derive(Debug, Clone, Deserialize, Serialize)]
27pub struct FaceResponse {
28    #[serde(default)]
29    pub(crate) errcode: i32,
30    #[serde(default)]
31    pub(crate) errmsg: String,
32    #[serde(flatten)]
33    pub extra: HashMap<String, Value>,
34}
35
36pub struct FaceApi {
37    context: Arc<WechatContext>,
38}
39
40impl FaceApi {
41    pub fn new(context: Arc<WechatContext>) -> Self {
42        Self { context }
43    }
44
45    pub async fn get_verify_id(
46        &self,
47        request: &GetVerifyIdRequest,
48    ) -> Result<FaceResponse, WechatError> {
49        self.post_json("/cgi-bin/soter/mp/verify_id/get", request)
50            .await
51    }
52
53    pub async fn query_verify_info(
54        &self,
55        request: &QueryVerifyInfoRequest,
56    ) -> Result<FaceResponse, WechatError> {
57        self.post_json("/cgi-bin/soter/mp/verify_result/get", request)
58            .await
59    }
60
61    async fn post_json<B: Serialize>(
62        &self,
63        endpoint: &str,
64        body: &B,
65    ) -> Result<FaceResponse, WechatError> {
66        let response: FaceResponse = self.context.authed_post(endpoint, body).await?;
67        WechatError::check_api(response.errcode, &response.errmsg)?;
68        Ok(response)
69    }
70}
71
72impl WechatApi for FaceApi {
73    fn context(&self) -> &WechatContext {
74        &self.context
75    }
76
77    fn api_name(&self) -> &'static str {
78        "face"
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn face_response_deserializes() {
88        let json = r#"{"errcode":0,"errmsg":"ok","verify_result":"pass"}"#;
89        let response: FaceResponse = serde_json::from_str(json).unwrap();
90        assert_eq!(response.errcode, 0);
91    }
92}