1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use crate::{
    app_cert_client, client_builder::ClientBuilder, error::AlipayResult, response::Response,
    util::datetime, AlipayParams, BoxFuture, Cli, ClientWithParams, Sign,
};
use futures::FutureExt;
use openssl::{
    base64,
    hash::MessageDigest,
    pkey::{PKey, Private, Public},
    rsa::Rsa,
    sign::{Signer, Verifier},
};
use serde_json::Value;
use std::collections::HashMap;

#[derive(Debug)]
pub struct Client {
    public_key: String,
    private_key: String,
    request_params: HashMap<String, String>,
    sandbox: bool,
}

impl Client {
    /// app_id: 可在支付宝控制台 -> 我的应用 中查看
    /// public_key: 支付宝开放平台开发助手生成的应用公钥钥文件
    /// private_key: 支付宝开放平台开发助手生成的应用私钥
    /// app_cert_sn: 在应用的 开发设置 -> 开发信息 -> 接口加签方式 中获取
    /// alipay_root_cert_sn: 同上
    pub fn new<S: Into<String>>(
        app_id: S,
        public_key: S,
        private_key: S,
        app_cert_sn: Option<S>,
        alipay_root_cert_sn: Option<S>,
        sandbox: bool,
    ) -> Client {
        let mut params: HashMap<String, String> = HashMap::from([
            ("app_id".to_owned(), app_id.into()),
            ("charset".to_owned(), "utf-8".to_owned()),
            ("sign_type".to_owned(), "RSA2".to_owned()),
            ("format".to_owned(), "json".to_owned()),
            ("version".to_owned(), "1.0".to_owned()),
        ]);

        if let Some(cert_sn) = app_cert_sn {
            let app_cert_sn = app_cert_client::get_cert_sn_from_content(cert_sn.into().as_bytes())
                .unwrap_or_else(|_| String::from(""));
            params.insert("app_cert_sn".to_owned(), app_cert_sn);
        }
        if let Some(root_cert_sn) = alipay_root_cert_sn {
            let alipay_root_cert_sn =
                app_cert_client::get_root_cert_sn_from_content(&root_cert_sn.into())
                    .unwrap_or_else(|_| String::from(""));
            params.insert("alipay_root_cert_sn".to_owned(), alipay_root_cert_sn);
        }
        Self {
            public_key: public_key.into(),
            private_key: private_key.into(),
            request_params: params,
            sandbox,
        }
    }

    /// app_id: 可在支付宝控制台 -> 我的应用 中查看
    /// public_key_path: 支付宝开放平台开发助手生成的应用公钥钥文件
    /// private_key_path: 支付宝开放平台开发助手生成的应用私钥文件
    /// app_cert_sn: 在应用的 开发设置 -> 开发信息 -> 接口加签方式 中获取
    /// alipay_root_cert_sn: 同上
    pub fn neo<S: Into<String>>(
        app_id: S,
        public_key_path: S,
        private_key_path: S,
        app_cert_sn: Option<S>,
        alipay_root_cert_sn: Option<S>,
        sandbox: bool,
    ) -> Client {
        let public_key = app_cert_client::get_file_content(&public_key_path.into())
            .unwrap_or_else(|_| String::from(""));
        let private_key = app_cert_client::get_file_content(&private_key_path.into())
            .unwrap_or_else(|_| String::from(""));
        let mut cert_sn: String = String::from("");
        if let Some(cert_sn_path) = app_cert_sn {
            cert_sn = app_cert_client::get_cert_sn(&cert_sn_path.into())
                .unwrap_or_else(|_| String::from(""));
        }
        let mut root_cert_sn: String = String::from("");
        if let Some(root_cert_sn_path) = alipay_root_cert_sn {
            root_cert_sn = app_cert_client::get_root_cert_sn(&root_cert_sn_path.into())
                .unwrap_or_else(|_| String::from(""));
        }
        Client::new(
            app_id.into(),
            public_key,
            private_key,
            Some(cert_sn),
            Some(root_cert_sn),
            sandbox,
        )
    }

    /// ```rust
    /// let client = alipay_rs::Client::builder()
    /// .app_id("2021002199679230")
    /// .public_key(include_str!("../公钥.txt"))
    /// .private_key(include_str!("../私钥.txt"))
    /// .app_cert_sn(include_str!("../appCertPublicKey_2021002199679230.crt"))
    /// .alipay_root_cert_sn(include_str!("../alipayRootCert.crt"))
    /// .finish();
    /// ```
    pub fn builder<'a>() -> ClientBuilder<'a> {
        ClientBuilder::default()
    }

    /// 设置/添加公共参数
    ///
    ///
    /// Example:
    /// ```rust
    /// #[derive(AlipayParams)]
    /// struct PublicParams {
    ///     app_id: String,
    ///     charset: String,
    ///     sign_type: String,
    ///     version: String,
    /// }
    ///
    /// ......
    ///
    ///     let public_params = PublicParams {
    ///         app_id: "20210xxxxxxxxxxx".to_owned(),
    ///         charset: "utf-8".to_owned(),
    ///         sign_type: "RSA2".to_owned(),
    ///         version: "1.0".to_owned(),
    ///     };
    ///
    ///     // 也可以通过vec, hashmap, array, tuple来设置公共参数
    ///     let public_params = ("app_id", "20210xxxxxxxxxxx");
    ///     let public_params = [("image_type", "png"), ("image_name", "test")];
    ///     let public_params = vec![("image_type", "png"), ("image_name", "test")];
    ///     let public_params = HashMap::from([("image_type", "png"), ("image_name", "test")]);
    ///
    ///     client.set_public_params(public_params);
    /// ```
    pub fn set_public_params<T>(&self, args: T) -> ClientWithParams
    where
        T: AlipayParams,
    {
        let params = args.to_alipay_value().to_json_value();
        let mut other_params = HashMap::new();

        if let Value::Object(v) = params {
            for (key, val) in v {
                other_params.insert(key, val);
            }
        }
        ClientWithParams::new(
            self.public_key.clone(),
            self.private_key.clone(),
            self.request_params.clone(),
            other_params,
            self.sandbox,
        )
    }

    fn alipay_post<S: Into<String>>(
        &self,
        method: S,
        biz_content: Option<String>,
    ) -> AlipayResult<Response> {
        let url = if !self.sandbox {
            "https://openapi.alipay.com/gateway.do"
        } else {
            "https://openapi.alipaydev.com/gateway.do"
        };
        let params = self.build_params(method.into(), biz_content)?;
        let res = ureq::post(url)
            .set(
                "Content-Type",
                "application/x-www-form-urlencoded;charset=utf-8",
            )
            .send_string(&params)?;

        Ok(Response::new(res))
    }
    fn create_params(
        &self,
        method: String,
        biz_content: Option<String>,
    ) -> AlipayResult<Vec<(String, String)>> {
        let request_params_len = self.request_params.len();

        let now = datetime()?;

        let mut params: Vec<(String, String)> = Vec::with_capacity(request_params_len + 3);

        params.push(("timestamp".to_string(), now));
        params.push(("method".to_string(), method));

        for (key, val) in self.request_params.iter() {
            params.push((key.to_string(), val.to_string()));
        }

        if let Some(content) = biz_content {
            params.push(("biz_content".to_string(), content));
        }

        params.sort_by(|a, b| a.0.cmp(&b.0));
        let mut temp = String::new();
        for (key, val) in params.iter() {
            temp.push_str(key);
            temp.push('=');
            temp.push_str(val);
            temp.push('&');
        }
        temp.pop();

        let sign = self.sign(&temp)?;
        params.push(("sign".to_owned(), sign));
        Ok(params)
    }
    fn build_params(&self, method: String, biz_content: Option<String>) -> AlipayResult<String> {
        let params = self.create_params(method, biz_content)?;
        Ok(serde_urlencoded::to_string(params)?)
    }

    fn get_private_key(&self) -> AlipayResult<PKey<Private>> {
        let cert_content = base64::decode_block(self.private_key.as_str())?;
        let rsa = Rsa::private_key_from_der(&cert_content)?;

        Ok(PKey::from_rsa(rsa)?)
    }
    fn get_public_key(&self) -> AlipayResult<PKey<Public>> {
        let cert_content = base64::decode_block(self.public_key.as_str())?;
        let rsa = Rsa::public_key_from_der(&cert_content)?;

        Ok(PKey::from_rsa(rsa)?)
    }
}

impl Sign for Client {
    fn sign(&self, params: &str) -> AlipayResult<String> {
        let private_key = self.get_private_key()?;
        let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?;
        signer.update(params.as_bytes())?;
        let sign = base64::encode_block(signer.sign_to_vec()?.as_ref());
        Ok(sign)
    }
    fn verify(&self, source: &str, signature: &str) -> AlipayResult<bool> {
        let public_key = self.get_public_key()?;
        let sign = base64::decode_block(signature)?;
        let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
        verifier.update(source.as_bytes())?;
        Ok(verifier.verify(sign.as_slice())?)
    }
}

impl Cli for Client {
    /// 异步请求
    ///
    /// 支付宝的官方接口都可以使用此函数访问
    ///
    /// Example:
    /// ```rust
    ///    let client = alipay_rs::Client::new(
    ///         "20210xxxxxxxxxxx",
    ///         include_str!("../公钥.txt"),
    ///         include_str!("../私钥.txt"),
    ///         Some(include_str!("../appCertPublicKey_20210xxxxxxxxxxx.crt")),
    ///         Some(include_str!("../alipayRootCert.crt"))
    ///     );
    ///     let data:serde_json::Value = client
    ///         .post("alipay.fund.trans.uni.transfer", transfer)
    ///         .await.unwrap().into_json().unwrap();
    ///
    ///     // 现在除了AlipayParams宏来设置参数外,还可以通过vec, hashmap, array, tuple来存储参数
    ///     // 如果没有参数可以传“()”,比如:client.post("method", ())
    ///     let params = ("app_id", "20210xxxxxxxxxxx");
    ///     let params = [("image_type", "png"), ("image_name", "test")];
    ///     let params = vec![("image_type", "png"), ("image_name", "test")];
    ///     let params = HashMap::from([("image_type", "png"), ("image_name", "test")]);
    /// ```
    fn post<'a, S, T>(&'a self, method: S, biz_content: T) -> BoxFuture<'a, AlipayResult<Response>>
    where
        S: Into<String> + Send + 'a,
        T: AlipayParams + Send + 'a,
    {
        async move { self.sync_post::<'a, S, T>(method, biz_content) }.boxed()
    }
    /// 没有参数的异步请求
    /// 此函数后期考虑放弃,请调用post函数。
    /// 如果没有参数,可以这样调用post,post("method", ()) 或 post("method", None)
    fn no_param_post<'a, S>(&'a self, method: S) -> BoxFuture<'a, AlipayResult<Response>>
    where
        S: Into<String> + Send + 'a,
    {
        async move { self.alipay_post::<S>(method, None) }.boxed()
    }
    /// 同步请求
    fn sync_post<'a, S, T>(&'a self, method: S, biz_content: T) -> AlipayResult<Response>
    where
        S: Into<String> + Send + 'a,
        T: AlipayParams + Send + 'a,
    {
        let biz_content = biz_content.to_alipay_value();
        if biz_content.is_null() {
            self.alipay_post::<S>(method, None)
        } else {
            self.alipay_post::<S>(
                method,
                Some(serde_json::to_string(&biz_content.to_json_value())?),
            )
        }
    }

    /// 文件上传
    /// method: 接口名称
    /// key: 文件参数名
    /// file_name: 文件名
    /// file_content: 文件内容
    ///
    /// ```rust
    /// #[derive(AlipayParams)]
    /// struct Image {
    ///     image_type: String,
    ///     image_name: String,
    /// }
    /// let file = std::fs::read("./test.png").unwrap();
    /// let image = Image {
    ///     image_type: "png".to_owned(),
    ///     image_name: "test".to_owned(),
    /// };
    /// let client = ...;
    /// let mut client_with_params = client.set_public_params(image);
    /// let data:serde_json::Value = client_with_params.post_file("alipay.offline.material.image.upload", "image_content", "test.png", file.as_ref()).await.unwrap().into_json().unwrap();
    /// println!("{:?}", data);
    /// ```
    fn post_file<'a, S>(
        &'a self,
        method: S,
        key: &'a str,
        file_name: &'a str,
        file_content: &'a [u8],
    ) -> BoxFuture<'a, AlipayResult<Response>>
    where
        S: Into<String> + Send + 'a,
    {
        async move {
            let mut multi = multipart::client::lazy::Multipart::new();
            multi.add_stream(key, file_content, Some(file_name), None);
            let mdata = multi.prepare()?;
            let mut url = if !self.sandbox {
                "https://openapi.alipay.com/gateway.do".to_owned()
            } else {
                "https://openapi.alipaydev.com/gateway.do".to_owned()
            };
            let params = self.build_params(method.into(), None)?;
            url.push('?');
            url.push_str(params.as_str());
            let res = ureq::post(url.as_str())
                .set(
                    "Content-Type",
                    &format!("multipart/form-data; boundary={}", mdata.boundary()),
                )
                .send(mdata)?;
            Ok(Response::new(res))
        }
        .boxed()
    }
    fn generate_url_data<'a, S, T>(
        &'a self,
        method: S,
        biz_content: T,
    ) -> AlipayResult<Vec<(String, String)>>
    where
        S: Into<String> + Send + 'a,
        T: AlipayParams + Send + 'a,
    {
        let biz_content = biz_content.to_alipay_value();
        let params = if biz_content.is_null() {
            self.create_params(method.into(), None)?
        } else {
            self.create_params(
                method.into(),
                Some(serde_json::to_string(&biz_content.to_json_value())?),
            )?
        };
        // let url = if !self.sandbox {
        //     "https://openapi.alipay.com/gateway.do".to_owned()
        // } else {
        //     "https://openapi.alipaydev.com/gateway.do".to_owned()
        // };
        // params.push(("url".to_owned(), url));
        Ok(params)
    }
}