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
/*!

支付宝当面付api对接,加解密采用RSA2,忽略了部分非必选参数.可以作为对接参考.
[具体参考alipay官方校验规则](https://opendocs.alipay.com/open/200/106120)

# Precreate
调用Alipay Precreate接口并校验应答
```rust
let biz_content = BizContent::new("16089520029516", "5", "测试商品", 0.2f32);
let req = PreCreateRequest::new(
    "2021002116638987",
    "20201228 14:33:22",
    "http://api.test.alipay.net/atinterface/receive_notify.htm",
    biz_content,
);
//读取自己生成的私钥
let pk = private_key("./app_private_key_pkcs8.pem");
//生成签名
assert!(req.sign(pk).is_ok());
//生成最终的请求报文
let url = format!("https://openapi.alipaydev.com/gateway.do?{}", req);
//使用任意支持Https请求的客户端发送请求
let resp = ureq::post(&url).call();
let resp = resp
    .into_json_deserialize::<PrecreateResponseWrap>()
    .unwrap();
assert_eq!(resp.alipay_trade_precreate_response.msg, "Success");
let pk = public_key("./alipay_public_key.pem");
//通过Alipay提供的公钥验证PrecreateResponse的正确性
assert!(resp.varify(pk).is_ok());
```

# AsyncNotifyCheck
收到来自Alipay的Notify请求后取出query_str后通过Alipay公钥进行校验
```rust
let req_query = "total_amount=2.00&buyer_id=2088102116773037&body=大乐透2.1&trade_no=2016071921001003030200089909&refund_fee=0.00&notify_time=2016-07-19 14:10:49&subject=大乐透2.1&sign_type=RSA2&charset=utf-8&notify_type=trade_status_sync&out_trade_no=0719141034-6418&gmt_close=2016-07-19 14:10:46&gmt_payment=2016-07-19 14:10:47&trade_status=TRADE_SUCCESS&version=1.0&sign=kPbQIjX+xQc8F0/A6/AocELIjhhZnGbcBN6G4MM/HmfWL4ZiHM6fWl5NQhzXJusaklZ1LFuMo+lHQUELAYeugH8LYFvxnNajOvZhuxNFbN2LhF0l/KL8ANtj8oyPM4NN7Qft2kWJTDJUpQOzCzNnV9hDxh5AaT9FPqRS6ZKxnzM=&gmt_create=2016-07-19 14:10:44&app_id=2015102700040153&seller_id=2088102119685838&notify_id=4a91b7a78a503640467525113fb7d8bg8e";
let nq = NotifyQuery::from(req_query);
let pk = public_key("./alipay_public_key.pem");
assert!(nq.varify(pk).is_ok());
```
*/

mod error;

pub use crate::error::{Error, Result};
use rsa::{Hash, PaddingScheme::PKCS1v15Sign, PublicKey, RSAPrivateKey, RSAPublicKey};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

// #[derive(Serialize, Deserialize, Debug)]
#[derive(Debug)]
pub struct BizContent<'a> {
    out_trade_no: &'a str,
    qr_code_timeout_express: &'a str,
    subject: &'a str,
    total_amount: f32,
}

impl<'a> BizContent<'a> {
    pub fn new(
        out_trade_no: &'a str,
        qr_code_timeout_express: &'a str,
        subject: &'a str,
        total_amount: f32,
    ) -> Self {
        Self {
            out_trade_no,
            qr_code_timeout_express,
            subject,
            total_amount,
        }
    }
}

impl<'a> std::fmt::Display for BizContent<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(
            f,
            r#"{{"out_trade_no":"{}","qr_code_timeout_express":"{}m","subject":"{}","total_amount":{}}}"#,
            self.out_trade_no, self.qr_code_timeout_express, self.subject, self.total_amount
        )
    }
}

#[inline]
fn varify(public_key: RSAPublicKey, content: &str, sig: &str) -> Result<()> {
    let mut sh = Sha256::new();
    sh.update(content);
    let hashed: &[u8] = &sh.finalize();
    let sig = base64::decode(sig)?;
    Ok(public_key.verify(
        PKCS1v15Sign {
            hash: Some(Hash::SHA2_256),
        },
        hashed,
        &sig,
    )?)
}

pub trait Signable {
    fn presigned_content(&self) -> String;
}
// #[derive(Serialize, Deserialize, Debug)]
#[derive(Debug)]
pub struct PreCreateRequest<'a> {
    app_id: &'a str,
    biz_content: BizContent<'a>,
    charset: &'a str,
    method: &'a str,
    notify_url: &'a str,
    sign_type: &'a str,
    sign: Option<String>,
    timestamp: &'a str,
    version: &'a str,
}

impl<'a> PreCreateRequest<'a> {
    pub fn new(
        app_id: &'a str,
        // method:&'a str,
        // charset:&'a str,
        // sign_type:&'a str,
        // sign:&'a str,
        timestamp: &'a str, //yyyy-MM-dd HH:mm:ss
        // version:&'a str,
        notify_url: &'a str,
        biz_content: BizContent<'a>,
    ) -> Self {
        Self {
            app_id,
            method: "alipay.trade.precreate",
            charset: "utf-8",
            sign_type: "RSA2",
            sign: None,
            timestamp,
            version: "1.0",
            notify_url,
            biz_content,
        }
    }

    pub fn sign(&mut self, pk: RSAPrivateKey) -> Result<()> {
        let mut sh = Sha256::new();
        sh.update(self.presigned_content());
        let hashed: &[u8] = &sh.finalize();
        let res = pk.sign(
            PKCS1v15Sign {
                hash: Some(Hash::SHA2_256),
            },
            hashed,
        )?;
        self.sign = Some(base64::encode(res));
        Ok(())
    }
}

impl<'a> Signable for PreCreateRequest<'a> {
    fn presigned_content(&self) -> String {
        format!(
            r#"app_id={}&biz_content={}&charset={}&method={}&notify_url={}&sign_type={}&timestamp={}&version={}"#,
            self.app_id,
            self.biz_content,
            self.charset,
            self.method,
            self.notify_url,
            self.sign_type,
            self.timestamp,
            self.version
        )
    }
}

impl<'a> std::fmt::Display for PreCreateRequest<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        if let Some(s) = &self.sign {
            let params = &[
                ("app_id", self.app_id),
                ("biz_content", &self.biz_content.to_string()),
                ("charset", self.charset),
                ("method", self.method),
                ("notify_url", self.notify_url),
                ("sign_type", self.sign_type),
                ("sign", s),
                ("timestamp", self.timestamp),
                ("version", self.version),
            ];
            if let Ok(query) = serde_urlencoded::to_string(params) {
                return write!(f, "{}", query);
            }
        }
        Err(std::fmt::Error)
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct PrecreateResponseWrap {
    pub alipay_trade_precreate_response: AlipayTradePrecreateResponse,
    pub sign: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct AlipayTradePrecreateResponse {
    code: String,
    msg: String,
    out_trade_no: String,
    qr_code: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    sub_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sub_msg: Option<String>,
}

impl PrecreateResponseWrap {
    pub fn varify(&self, public_key: RSAPublicKey) -> Result<()> {
        varify(
            public_key,
            &self.alipay_trade_precreate_response.presigned_content(),
            &self.sign,
        )
    }
}

impl Signable for AlipayTradePrecreateResponse {
    fn presigned_content(&self) -> String {
        let mut c = format!(
            r#"{{"code":"{}","msg":"{}","out_trade_no":"{}","qr_code":"{}""#,
            self.code,
            self.msg,
            self.out_trade_no,
            self.qr_code.replace("/", "\\/")
        );
        if let Some(sub_code) = &self.sub_code {
            c.push_str(&format!(r#","sub_code":"{}""#, sub_code));
        }
        if let Some(sub_msg) = &self.sub_msg {
            c.push_str(&format!(r#","sub_msg":"{}""#, sub_msg));
        }
        c.push_str("}");
        c
    }
}

#[derive(Debug)]
pub struct NotifyQuery {
    pub query_map: std::collections::BTreeMap<String, String>,
}

impl NotifyQuery {
    pub fn varify(&self, public_key: RSAPublicKey) -> Result<()> {
        match (self.query_map.get("sign"), self.query_map.get("sign_type")) {
            (Some(sig), Some(t)) if t == "RSA2" => {
                varify(public_key, &self.presigned_content(), sig)
            }
            _ => Err(Error::Rsa(rsa::errors::Error::Verification)),
        }
    }
}

impl From<&str> for NotifyQuery {
    fn from(query: &str) -> Self {
        let ql = query.split('&');
        let mut query_map = std::collections::BTreeMap::new();
        for i in ql {
            let mut kv = i.splitn(2, '=');
            match (kv.next(), kv.next()) {
                (Some(k), Some(v)) => {
                    query_map.insert(k.to_owned(), v.to_owned());
                }
                _ => {}
            }
        }
        NotifyQuery { query_map }
    }
}

impl Signable for NotifyQuery {
    fn presigned_content(&self) -> String {
        let ql = self
            .query_map
            .iter()
            .filter(|(k, _)| **k != "sign" && **k != "sign_type")
            .map(|(k, v)| format!("{}={}", k, v))
            .collect::<Vec<_>>();
        ql.join("&")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{FixedOffset, Utc};
    use std::io::Read;
    fn current() -> String {
        Utc::now()
            .with_timezone(&FixedOffset::east(8 * 3600))
            .format("%Y-%m-%d %H:%M:%S")
            .to_string()
    }

    fn private_key(path: &str) -> RSAPrivateKey {
        let mut f = std::fs::File::open(path).unwrap();
        let mut content = String::default();
        f.read_to_string(&mut content).unwrap();
        let der_encoded = content.lines().filter(|line| !line.starts_with("-")).fold(
            String::new(),
            |mut data, line| {
                data.push_str(&line);
                data
            },
        );
        let der_bytes = base64::decode(&der_encoded).expect("failed to decode base64 content");
        RSAPrivateKey::from_pkcs8(&der_bytes).unwrap()
    }

    fn public_key(path: &str) -> RSAPublicKey {
        let mut f = std::fs::File::open(path).unwrap();
        let mut content = String::default();
        f.read_to_string(&mut content).unwrap();
        let der_encoded = content.lines().filter(|line| !line.starts_with("-")).fold(
            String::new(),
            |mut data, line| {
                data.push_str(&line);
                data
            },
        );
        let der_bytes = base64::decode(&der_encoded).expect("failed to decode base64 content");
        RSAPublicKey::from_pkcs8(&der_bytes).expect("failed to parse key")
    }

    fn create_request<'a>(timestamp: &'a str) -> PreCreateRequest<'a> {
        let biz_content = BizContent::new("16089520029516", "5", "测试商品", 0.2f32);
        PreCreateRequest::new(
            "2021002116638987",
            timestamp,
            "http://api.test.alipay.net/atinterface/receive_notify.htm",
            biz_content,
        )
    }
    #[test]
    fn precreate_test() {
        let timestamp = current();
        let mut req = create_request(&timestamp);
        let pk = private_key("/Users/tianen/dev/secret/app_private_key_pkcs8.pem");
        assert!(req.sign(pk).is_ok());
        let url = format!("https://openapi.alipay.com/gateway.do?{}", req);
        let resp = ureq::post(&url).call();
        let resp = resp
            .into_json_deserialize::<PrecreateResponseWrap>()
            .unwrap();
        assert_eq!(resp.alipay_trade_precreate_response.msg, "Success");
        let pk = public_key("/Users/tianen/dev/secret/alipay_public_key.pem");
        assert!(resp.varify(pk).is_ok());
    }

    #[test]
    fn async_notify_check_test() {
        let req_query = "total_amount=2.00&buyer_id=2088102116773037&body=大乐透2.1&trade_no=2016071921001003030200089909&refund_fee=0.00&notify_time=2016-07-19 14:10:49&subject=大乐透2.1&sign_type=RSA2&charset=utf-8&notify_type=trade_status_sync&out_trade_no=0719141034-6418&gmt_close=2016-07-19 14:10:46&gmt_payment=2016-07-19 14:10:47&trade_status=TRADE_SUCCESS&version=1.0&sign=kPbQIjX+xQc8F0/A6/AocELIjhhZnGbcBN6G4MM/HmfWL4ZiHM6fWl5NQhzXJusaklZ1LFuMo+lHQUELAYeugH8LYFvxnNajOvZhuxNFbN2LhF0l/KL8ANtj8oyPM4NN7Qft2kWJTDJUpQOzCzNnV9hDxh5AaT9FPqRS6ZKxnzM=&gmt_create=2016-07-19 14:10:44&app_id=2015102700040153&seller_id=2088102119685838&notify_id=4a91b7a78a503640467525113fb7d8bg8e";
        let nq = NotifyQuery::from(req_query);
        let pk = public_key("./alipay_public_key.pem");
        assert!(nq.varify(pk).is_ok());
    }
}