Skip to content

Commit

Permalink
Merge pull request #20 from wslongchen/develop
Browse files Browse the repository at this point in the history
合并分支
  • Loading branch information
wslongchen authored Oct 14, 2022
2 parents 8c116e4 + deb3561 commit c42c826
Show file tree
Hide file tree
Showing 14 changed files with 442 additions and 64 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "labrador"
version = "0.2.0"
version = "0.2.1"
authors = ["mrpan <1049058427@qq.com>"]
edition = "2018"
description = "Labrador - Mini thirdpart client for rust."
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Labrador &emsp; [![Docs][docs-image]][docs-url] [![Build Status]][actions] [![Latest Version]][crates.io] [![labrador: rustc 1.13+]][Rust 1.13]

[Build Status]: https://img.shields.io/docsrs/labrador/0.1.0?style=plastic
[Build Status]: https://img.shields.io/docsrs/labrador/0.2.0?style=plastic
[actions]: https://github.com/wslongchen/labrador/actions?query=branch%3Amaster
[Latest Version]: https://img.shields.io/crates/v/labrador?style=plastic
[crates.io]: https://crates.io/crates/labrador
Expand Down
2 changes: 1 addition & 1 deletion src/alipay/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ impl <T: SessionStore> AlipayClient<T> {
Ok(pem) => {
let cert = pem.parse_x509()?;
let algorithm = cert.signature_algorithm.oid().to_string();
if algorithm.ne("1.2.840.113549.1.1.11") && algorithm.ne("1.2.840.113549.1.1.5") {
if algorithm.starts_with("1.2.840.113549.1.1") {
continue;
}
let issuer = iter2string(cert.issuer())?;
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,5 @@ pub use reqwest::multipart::{Form, Part};
pub use bytes;
pub use serde_urlencoded;
pub use urlencoding;
pub use dashmap;
pub use dashmap;
pub use redis;
27 changes: 1 addition & 26 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,10 +325,7 @@ impl <T> LabraRequest <T> where T: Serialize {
client = client.add_root_certificate(cert.reqwest_cert()?);
}
let client = client.build()?;
let mut request = client.request(self.method.clone().into(), http_url.to_owned()).header(
reqwest::header::CONTENT_TYPE,
self.req_type.get_content_type(),
);
let mut request = client.request(self.method.clone().into(), http_url.to_owned());
let mut data = &self.body.to_string();
match self.body {
RequestBody::Json(v) => {
Expand All @@ -351,28 +348,6 @@ impl <T> LabraRequest <T> where T: Serialize {
}
RequestBody::Null => {}
}
// if let Some(data) = &self.data {
// match self.req_type {
// RequestType::Json => {
// request = request.json(data);
// }
// RequestType::Form => {
// let value = serde_json::to_value(data.clone()).unwrap_or(Value::Null);
// if value.is_string() {
// let v = value.to_string();
// request = request.body(v.replace("\"",""));
// } {
// request = request.form(data);
// }
// }
// RequestType::Multipart => {
//
// }
// _ => {
// request = request.body(serde_json::to_string(data).unwrap_or_default())
// }
// }
// }
if let Some(headers) = &self.headers {
for (k, v) in headers.into_iter() {
request = request.header(k, HeaderValue::from_str(v)?);
Expand Down
361 changes: 358 additions & 3 deletions src/session.rs

Large diffs are not rendered by default.

7 changes: 3 additions & 4 deletions src/wechat/cp/api/external_contact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,9 +503,8 @@ impl<'a, T: SessionStore> WechatCpExternalContact<'a, T> {
/// 企业可通过此接口向客户标签库中添加新的标签组和标签,每个企业最多可配置3000个企业标签。
/// 暂不支持第三方调用。
/// </pre>
pub async fn add_corp_tag(&self, req: WechatCpUserExternalTagGroupInfo) -> LabradorResult<WechatCpUserExternalTagGroupInfo> {
let v = self.client.post(WechatCpMethod::ExternalContact(CpExternalContactMethod::AddCorpTag), vec![], req, RequestType::Json).await?.json::<Value>()?;
WechatCommonResponse::parse::<WechatCpUserExternalTagGroupInfo>(v)
pub async fn add_corp_tag(&self, req: TagGroup) -> LabradorResult<WechatCommonResponse> {
self.client.post(WechatCpMethod::ExternalContact(CpExternalContactMethod::AddCorpTag), vec![], req, RequestType::Json).await?.json::<WechatCommonResponse>()
}

/// <pre>
Expand Down Expand Up @@ -1266,7 +1265,7 @@ pub struct WechatCpWelcomeMsg {

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WechatCpUserExternalTagGroupInfo {
pub tag_group: Option<TagGroup>,
pub tag_group: Option<Vec<TagGroup>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down
2 changes: 1 addition & 1 deletion src/wechat/cp/api/media.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ pub struct WechatCpMediaResponse {
#[serde(rename="type")]
pub r#type: Option<String>,
pub thumb_media_id: Option<String>,
pub created_at: Option<i64>,
pub created_at: Option<String>,
}


Expand Down
9 changes: 4 additions & 5 deletions src/wechat/cp/api/oauth2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ pub struct WechatCpOauth2<'a, T: SessionStore> {

#[allow(unused)]
impl<'a, T: SessionStore> WechatCpOauth2<'a, T> {

#[inline]
pub fn new(client: &WechatCpClient<T>) -> WechatCpOauth2<T> {
WechatCpOauth2 {
Expand Down Expand Up @@ -116,23 +115,23 @@ impl<'a, T: SessionStore> WechatCpOauth2<'a, T> {
let v = self.client.post(WechatCpMethod::Oauth2(CpOauth2Method::GetAuthUserDetail), vec![], json!({USER_TICKET: user_ticket}), RequestType::Json).await?.json::<Value>()?;
WechatCommonResponse::parse::<WechatCpUserDetail>(v)
}

}

//----------------------------------------------------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WechatCpOauth2UserInfo {
#[serde(alias="OpenId", alias="openid")]
#[serde(alias = "OpenId", alias = "openid")]
pub openid: Option<String>,
pub external_userid: Option<String>,
#[serde(alias="UserId", alias="userid")]
#[serde(alias = "UserId", alias = "userid")]
pub user_id: Option<String>,
pub user_ticket: Option<String>,
pub expires_in: Option<i64>,
#[serde(rename="DeviceId")]
#[serde(rename = "DeviceId")]
pub device_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WechatCpUserDetail {
/// 成员UserID
Expand Down
11 changes: 6 additions & 5 deletions src/wechat/cp/api/tag.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use serde::{Serialize, Deserialize};
use serde_json::{json, Value};

use crate::{session::SessionStore, request::{RequestType}, WechatCommonResponse, LabradorResult, WechatCpClient};
use crate::{session::SessionStore, request::{RequestType}, WechatCommonResponse, LabradorResult, WechatCpClient, LabraError};
use crate::wechat::cp::method::{CpTagMethod, WechatCpMethod};

/// 标签相关
Expand Down Expand Up @@ -81,7 +81,8 @@ impl<'a, T: SessionStore> WechatCpTag<'a, T> {
/// 获得标签列表.
pub async fn list_all(&self) -> LabradorResult<Vec<WechatCpTagInfo>> {
let v = self.client.get(WechatCpMethod::Tag(CpTagMethod::List), vec![], RequestType::Json).await?.json::<Value>()?;
WechatCommonResponse::parse::<Vec<WechatCpTagInfo>>(v)
let v = WechatCommonResponse::parse::<Value>(v)?;
serde_json::from_value::<Vec<WechatCpTagInfo>>(v["taglist"].to_owned()).map_err(LabraError::from)
}
}

Expand All @@ -90,7 +91,7 @@ impl<'a, T: SessionStore> WechatCpTag<'a, T> {
#[derive(Debug, Clone,Serialize, Deserialize)]
pub struct WechatCpTagGetResponse {
/// 用户列表
pub userid: Vec<WechatCpUserInfo>,
pub userlist: Vec<WechatCpUserInfo>,
/// 部门列表
pub partylist: Vec<i32>,
pub tagname: Option<String>,
Expand All @@ -106,8 +107,8 @@ pub struct WechatCpTagAddOrRemoveUsersResponse {

#[derive(Debug, Clone,Serialize, Deserialize)]
pub struct WechatCpTagInfo {
pub tagid: Option<String>,
pub tagname: Option<Vec<String>>,
pub tagid: Option<i32>,
pub tagname: Option<String>,
}

/// 微信用户信息
Expand Down
2 changes: 2 additions & 0 deletions src/wechat/cp/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub enum WechatCpMethod {
GetOrder,
GetOrderList,
GetCustomizedAuthUrl,
GetAuthUserInfo3rd,
Media(CpMediaMethod),
Tag(CpTagMethod),
Agent(CpAgentMethod),
Expand Down Expand Up @@ -58,6 +59,7 @@ impl RequestMethod for WechatCpMethod {
WechatCpMethod::GetCallbackIp => String::from("/cgi-bin/getcallbackip"),
WechatCpMethod::GetAgentConfigTicket => String::from("/cgi-bin/ticket/get?&type=agent_config"),
WechatCpMethod::GetCustomizedAuthUrl => String::from("/cgi-bin/service/get_customized_auth_url"),
WechatCpMethod::GetAuthUserInfo3rd => String::from("/cgi-bin/service/auth/getuserinfo3rd"),
WechatCpMethod::Media(v) => v.get_method(),
WechatCpMethod::ExternalContact(v) => v.get_method(),
WechatCpMethod::Oauth2(v) => v.get_method(),
Expand Down
42 changes: 42 additions & 0 deletions src/wechat/cp/tp/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::{LabradorResult, request::RequestType, session::SessionStore, WechatCommonResponse, WechatCpTpClient};
use crate::wechat::cp::constants::{CODE, PROVIDER_ACCESS_TOKEN};
use crate::wechat::cp::method::WechatCpMethod;

#[derive(Debug, Clone)]
pub struct WechatCpTpAuth<'a, T: SessionStore> {
client: &'a WechatCpTpClient<T>,
}

#[allow(unused)]
impl<'a, T: SessionStore> WechatCpTpAuth<'a, T> {
#[inline]
pub fn new(client: &WechatCpTpClient<T>) -> WechatCpTpAuth<T> {
WechatCpTpAuth {
client,
}
}

/// <pre>
/// 获取访问用户身份
/// <a href="https://developer.work.weixin.qq.com/document/path/91121">获取访问用户身份</a>
/// 该接口用于根据code获取成员信息,适用于自建应用与代开发应用
pub async fn get_user_info_auth_3rd(&self, code: &str) -> LabradorResult<WechatCpOauth2UserInfo3rd> {
let v = self.client.get(WechatCpMethod::GetAuthUserInfo3rd, vec![(CODE.to_string(), code.to_string())], RequestType::Json).await?.json::<Value>()?;
WechatCommonResponse::parse::<WechatCpOauth2UserInfo3rd>(v)
}
}

//----------------------------------------------------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WechatCpOauth2UserInfo3rd {
pub corpid: Option<String>,
#[serde(alias = "UserId", alias = "userid")]
pub user_id: Option<String>,
pub user_ticket: Option<String>,
pub expires_in: Option<i64>,
pub open_userid: Option<String>,
}
31 changes: 17 additions & 14 deletions src/wechat/cp/tp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod department;
mod user;
mod order;
mod agent;
mod auth;

pub use tag::*;
pub use license::*;
Expand All @@ -22,6 +23,7 @@ pub use department::*;
pub use user::*;
pub use order::*;
pub use agent::*;
use crate::wechat::cp::tp::auth::WechatCpTpAuth;


/// 企业微信第三方应用API
Expand All @@ -44,7 +46,6 @@ pub struct WechatCpTpClient<T: SessionStore> {

#[allow(unused)]
impl<T: SessionStore> WechatCpTpClient<T> {

fn from_client(client: APIClient<T>) -> WechatCpTpClient<T> {
WechatCpTpClient {
corp_id: client.app_key.to_owned(),
Expand All @@ -54,7 +55,7 @@ impl<T: SessionStore> WechatCpTpClient<T> {
suite_id: None,
suite_secret: None,
client,
provider_secret: None
provider_secret: None,
}
}

Expand Down Expand Up @@ -111,7 +112,7 @@ impl<T: SessionStore> WechatCpTpClient<T> {
/// 授权企业的access token相关
fn get_access_token(&self, auth_corp_id: &str) -> String {
let session = self.client.session();
session.get::<_,String>(self.key_with_prefix(auth_corp_id) + ACCESS_TOKEN_KEY, None).unwrap_or(None).unwrap_or_default()
session.get::<_, String>(self.key_with_prefix(auth_corp_id) + ACCESS_TOKEN_KEY, None).unwrap_or(None).unwrap_or_default()
}

/// <pre>
Expand Down Expand Up @@ -140,7 +141,7 @@ impl<T: SessionStore> WechatCpTpClient<T> {
let timestamp = current_timestamp();
let expires_at: i64 = session.get(&expires_key, Some(timestamp))?.unwrap_or_default();
if expires_at <= timestamp {
return Err(LabraError::ApiError("invaild suite ticket".to_string()))
return Err(LabraError::ApiError("invaild suite ticket".to_string()));
}
Ok(token)
}
Expand Down Expand Up @@ -199,7 +200,8 @@ impl<T: SessionStore> WechatCpTpClient<T> {
"suite_secret": self.suite_secret,
"suite_ticket": suite_ticket
});
let result = self.client.post(WechatCpMethod::GetSuiteToken, vec![], req, RequestType::Json).await?.json::<WechatCpSuiteAccessTokenResponse>()?;
let result = self.client.post(WechatCpMethod::GetSuiteToken, vec![], req, RequestType::Json).await?.json::<Value>()?;
let result = WechatCommonResponse::parse::<WechatCpSuiteAccessTokenResponse>(result)?;
let token = result.suite_access_token;
let expires_in = result.expires_in;
// 预留200秒的时间
Expand Down Expand Up @@ -280,12 +282,11 @@ impl<T: SessionStore> WechatCpTpClient<T> {
}



/// <pre>
/// 获取企业凭证
/// </pre>
pub async fn get_corp_token(&self, auth_corpid: &str, permanent_code: &str) -> LabradorResult<AccessTokenResponse> {
self.get_corp_token_force(auth_corpid, permanent_code,false).await
self.get_corp_token_force(auth_corpid, permanent_code, false).await
}

/// <pre>
Expand Down Expand Up @@ -314,7 +315,7 @@ impl<T: SessionStore> WechatCpTpClient<T> {
session.set(&expires_key, expires_at, Some(expires_in as usize));
Ok(result)
} else {
Ok(AccessTokenResponse{ access_token: token.to_string(), expires_in: expires_at })
Ok(AccessTokenResponse { access_token: token.to_string(), expires_in: expires_at })
}
}

Expand Down Expand Up @@ -485,8 +486,8 @@ impl<T: SessionStore> WechatCpTpClient<T> {
let noncestr = get_nonce_str();
let signature = WechatCrypto::get_sha1_sign(&vec!["jsapi_ticket=".to_string() + &jsapi_ticket,
"noncestr=".to_string() + &noncestr,
"timestamp=".to_string() + &timestamp.to_string(),"url=".to_string() + &url].join("&"));
JsapiSignature{
"timestamp=".to_string() + &timestamp.to_string(), "url=".to_string() + &url].join("&"));
JsapiSignature {
app_id: auth_corp_id.to_string(),
nonce_str: noncestr,
url: url.to_string(),
Expand Down Expand Up @@ -567,6 +568,11 @@ impl<T: SessionStore> WechatCpTpClient<T> {
pub fn agent(&self) -> WechatCpTpAgent<T> {
WechatCpTpAgent::new(self)
}

/// 身份
pub fn auth(&self) -> WechatCpTpAuth<T> {
WechatCpTpAuth::new(self)
}
}

//----------------------------------------------------------------------------------------------------------------------------
Expand All @@ -592,7 +598,7 @@ pub struct WechatCpThirdPermanentCodeInfo {
pub edition_info: Option<EditionInfo>,
pub expires_in: Option<i64>,
/// 安装应用时,扫码或者授权链接中带的state值。详见state说明
pub state: Option<String>
pub state: Option<String>,
}


Expand Down Expand Up @@ -731,7 +737,6 @@ pub struct WechatCpThirdPreauthCode {
}



/// 服务商模式获取授权信息
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WechatCpThirdAuthInfo {
Expand All @@ -746,8 +751,6 @@ pub struct WechatCpThirdAuthInfo {
}




/// 服务商模式获取授权信息
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DealerCorpInfo {
Expand Down
5 changes: 3 additions & 2 deletions src/wechat/cp/tp/tag.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde_json::{json, Value};

use crate::{session::SessionStore, request::{RequestType}, WechatCommonResponse, LabradorResult, WechatCpTpClient, WechatCpTagAddOrRemoveUsersResponse, WechatCpTagGetResponse, WechatCpTagInfo};
use crate::{session::SessionStore, request::{RequestType}, WechatCommonResponse, LabradorResult, WechatCpTpClient, WechatCpTagAddOrRemoveUsersResponse, WechatCpTagGetResponse, WechatCpTagInfo, LabraError};
use crate::wechat::cp::method::{CpTagMethod, WechatCpMethod};

/// 企业微信第三方开发-标签相关
Expand Down Expand Up @@ -80,7 +80,8 @@ impl<'a, T: SessionStore> WechatCpTpTag<'a, T> {
/// 获得标签列表.
pub async fn list_all(&self) -> LabradorResult<Vec<WechatCpTagInfo>> {
let v = self.client.get(WechatCpMethod::Tag(CpTagMethod::List), vec![], RequestType::Json).await?.json::<Value>()?;
WechatCommonResponse::parse::<Vec<WechatCpTagInfo>>(v)
let v = WechatCommonResponse::parse::<Value>(v)?;
serde_json::from_value::<Vec<WechatCpTagInfo>>(v["taglist"].to_owned()).map_err(LabraError::from)
}
}

Expand Down

0 comments on commit c42c826

Please sign in to comment.