1use br_reqwest::Client;
2use std::collections::{HashMap};
3use base64::{Engine};
4use base64::engine::general_purpose::STANDARD;
5use chrono::{Local};
6use crate::{PayMode, PayNotify, RefundNotify, RefundStatus, TradeState, TradeType, Types};
7use json::{array, object, JsonValue};
8use openssl::hash::MessageDigest;
9use openssl::pkey::{PKey};
10use openssl::rsa::Rsa;
11use openssl::sign::{Signer};
12use urlencoding::{encode};
13use log::error;
14
15#[derive(Clone, Debug)]
16pub struct AliPay {
17 pub appid: String,
19 pub sp_mchid: String,
21 pub app_auth_token: String,
23 pub app_private: String,
25 pub content_encryp: String,
27 pub alipay_public_key: String,
29 pub notify_url: String,
30}
31impl AliPay {
32 pub fn sign(&mut self, txt: &str) -> Result<JsonValue, String> {
33 let t = self.app_private.as_bytes().chunks(64).map(|chunk| std::str::from_utf8(chunk).unwrap_or("")).collect::<Vec<&str>>().join("\n");
34 let cart = format!("-----BEGIN PRIVATE KEY-----\n{t}\n-----END PRIVATE KEY-----\n");
35
36 let rsa = match Rsa::private_key_from_pem(cart.as_bytes()) {
38 Ok(e) => e,
39 Err(e) => return Err(e.to_string())
40 };
41
42 let pkey = match PKey::from_rsa(rsa) {
43 Ok(e) => e,
44 Err(e) => return Err(e.to_string())
45 };
46
47 let mut signer = match Signer::new(MessageDigest::sha256(), &pkey) {
49 Ok(e) => e,
50 Err(e) => return Err(e.to_string())
51 };
52 match signer.update(txt.as_bytes()) {
53 Ok(()) => {}
54 Err(e) => return Err(e.to_string())
55 };
56 let signature = match signer.sign_to_vec() {
58 Ok(e) => e,
59 Err(e) => return Err(e.to_string())
60 };
61 Ok(STANDARD.encode(signature).into())
63 }
64 pub fn http(&mut self, method: &str, biz_content: JsonValue) -> Result<JsonValue, String> {
65 let mut http = Client::new();
66 let sign = "";
68
69 let now = Local::now();
70 let timestamp = now.format("%Y-%m-%d %H:%M:%S").to_string();
71
72 let mut data = object! {
73 "charset":"UTF-8",
74 "method":method,
75 "app_id":self.appid.clone(),
76 "app_private_key":self.app_private.clone(),
77 "version":"1.0",
78 "sign_type":"RSA2",
79 "timestamp":timestamp,
80 "alipay_public_key":self.alipay_public_key.clone(),
81 "sign":sign
82 };
83 if !self.app_auth_token.is_empty() {
84 data["app_auth_token"] = self.app_auth_token.clone().into();
85 }
86 if method.contains("alipay.trade.") {
87 data["notify_url"] = self.notify_url.clone().into();
88 }
89 for (key, value) in biz_content.entries() {
90 data[key] = value.clone()
91 }
92 let mut map = HashMap::new();
93 for (key, value) in data.entries() {
94 if key == "sign" {
95 continue;
96 }
97 if value.is_empty() {
98 continue;
99 }
100 map.insert(key, value);
101 }
102
103 let mut keys: Vec<_> = map.keys().cloned().collect();
104 keys.sort();
105 let mut txt = vec![];
106 for key in keys {
107 txt.push(format!("{}={}", key, map.get(&key).unwrap()));
108 }
109 let txt = txt.join("&");
110 data["sign"] = self.sign(&txt)?;
111
112 let mut new_data = object! {};
113 for (key, value) in data.entries() {
114 let t = encode(value.to_string().as_str()).to_string();
115 new_data[key] = t.into();
116 }
117 data = new_data;
118 let url = "https://openapi.alipay.com/gateway.do".to_string();
119 let res = match method {
120 "alipay.trade.wap.pay" => {
121 let tt = http.get(url.as_str()).query(data);
122 return Ok(tt.url.clone().into());
123 }
124 _ => {
125 match http.get(&url).query(data).form_data(biz_content).send() {
126 Ok(e) => e,
127 Err(e) => return Err(e.to_string())
128 }
129 }
130 };
131
132 let res = res.json()?;
133 if res.has_key("error_response") {
134 return Err(res["error_response"]["sub_msg"].to_string());
135 }
136 let key = method.replace(".", "_");
137 let key = format!("{key}_response");
138 let data = res[key].clone();
139 if data.has_key("code") {
140 if data["code"] != "10000" {
141 Err(data["sub_msg"].to_string())
142 } else {
143 Ok(data)
144 }
145 } else {
146 Err(data.to_string())
147 }
148 }
149 pub fn https(&mut self, method: &str, biz_content: JsonValue) -> Result<JsonValue, String> {
150 let mut http = Client::new();
151 let sign = "";
153
154 let now = Local::now();
155 let timestamp = now.format("%Y-%m-%d %H:%M:%S").to_string();
156
157 let mut data = object! {
158 "charset":"UTF-8",
159 "method":method,
160 "app_id":self.appid.clone(),
161 "app_private_key":self.app_private.clone(),
162 "version":"1.0",
163 "sign_type":"RSA2",
164 "timestamp":timestamp,
165 "alipay_public_key":self.alipay_public_key.clone(),
166 "sign":sign
167 };
168 if !self.app_auth_token.is_empty() {
169 data["app_auth_token"] = self.app_auth_token.clone().into();
170 }
171 if method.contains("alipay.trade.") {
172 data["notify_url"] = self.notify_url.clone().into();
173 }
174 for (key, value) in biz_content.entries() {
175 data[key] = value.clone()
176 }
177 let mut map = HashMap::new();
178 for (key, value) in data.entries() {
179 if key == "sign" {
180 continue;
181 }
182 if value.is_empty() {
183 continue;
184 }
185 map.insert(key, value);
186 }
187
188 let mut keys: Vec<_> = map.keys().cloned().collect();
189 keys.sort();
190 let mut txt = vec![];
191 for key in keys {
192 txt.push(format!("{}={}", key, map.get(&key).unwrap()));
193 }
194 let txt = txt.join("&");
195 data["sign"] = self.sign(&txt)?;
196
197 let mut new_data = object! {};
198 for (key, value) in data.entries() {
199 let t = encode(value.to_string().as_str()).to_string();
200 new_data[key] = t.into();
201 }
202 data = new_data;
203 let url = "https://openapi.alipay.com/gateway.do".to_string();
204 let res = match method {
205 "alipay.trade.wap.pay" => {
206 let tt = http.get(url.as_str()).query(data);
207 return Ok(tt.url.clone().into());
208 }
209 _ => {
210 match http.get(&url).query(data).form_data(biz_content).send() {
211 Ok(e) => e,
212 Err(e) => return Err(e.to_string())
213 }
214 }
215 };
216
217 let res = res.json()?;
218 if res.has_key("error_response") {
219 return Err(res["error_response"]["sub_msg"].to_string());
220 }
221 let key = method.replace(".", "_");
222 let key = format!("{key}_response");
223 let data = res[key].clone();
224 Ok(data)
225 }
226}
227impl PayMode for AliPay {
228 fn check(&mut self) -> Result<bool, String> {
229 let biz_content = object! {
230 "biz_content":{
231 "grant_type":"authorization_code",
232 "code":"123"
233 }
234 };
235 match self.http("alipay.open.auth.token.app", biz_content) {
236 Ok(e) => e,
237 Err(e) => {
238 if e.contains("auth_code不存在") {
239 return Ok(true);
240 }
241 return Err(e);
242 }
243 };
244 Ok(true)
245 }
246
247 fn get_sub_mchid(&mut self, sub_mchid: &str) -> Result<JsonValue, String> {
248 let res = self.https("alipay.open.agent.signstatus.query", object! {
249 "biz_content":{
250 "pid":sub_mchid,
251 "product_codes":array!["QUICK_WAP_WAY"]
252 }
253 })?;
254 if !res["code"].eq("10000") {
255 return Err(res["msg"].to_string());
256 }
257 for item in res["sign_status_list"].members() {
258 if item["status"].eq("none") {
259 return Err(format!("{} 未开通", res["product_name"]));
260 }
261 }
262 Ok(true.into())
263 }
264
265
266 fn config(&mut self) -> JsonValue {
267 todo!()
268 }
269
270 fn auth(&mut self, code: &str) -> Result<JsonValue, String> {
271 let biz_content = object! {
272 "biz_content":{
273 "grant_type":"authorization_code",
274 "code":code
275 }
276 };
277 let res = match self.http("alipay.open.auth.token.app", biz_content) {
278 Ok(e) => e,
279 Err(e) => {
280 error!("Err: {e:#}");
281 return Err(e);
282 }
283 };
284
285 let data = object! {
286 data:res.clone(),
287 user_id : res["user_id"].clone(),
288 auth_app_id : res["auth_app_id"].clone(),
289 re_expires_in :res["re_expires_in"].clone(),
290 app_auth_token:res["app_auth_token"].clone(),
291 app_refresh_token:res["app_refresh_token"].clone()
292 };
293 Ok(data)
294 }
295
296 fn pay(&mut self, _channel: &str, types: Types, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, sp_openid: &str) -> Result<JsonValue, String> {
297 let mut api = "";
298 let mut order = object! {
299 out_trade_no:out_trade_no,
300 total_amount:total_fee,
301 subject:description,
302 product_code:"JSAPI_PAY",
303 op_app_id:sub_mchid,
304 buyer_open_id:sp_openid
305 };
306
307 match types {
308 Types::MiniJsapi => {
309 api = "alipay.trade.create";
310 order["product_code"] = "JSAPI_PAY".into();
311 order["op_app_id"] = self.appid.clone().into();
312 order["buyer_open_id"] = sp_openid.into();
313 self.app_auth_token = "".to_string();
314 }
315 Types::Jsapi => {
316 api = "alipay.trade.create";
317 order["product_code"] = "JSAPI_PAY".into();
318 }
319 Types::H5 => {
320 api = "alipay.trade.wap.pay";
321 order["product_code"] = "QUICK_WAP_WAY".into();
322 }
323 Types::Native => {
324 api = "alipay.trade.wap.pay";
325 order["product_code"] = "QUICK_WAP_WAY".into();
326 }
327 _ => {
328 order["product_code"] = "JSAPI_PAY".into();
329 }
330 };
331 match self.http(api, object! {"biz_content":order}) {
332 Ok(e) => {
333 match types {
334 Types::Jsapi => {}
335 Types::Native => {}
336 Types::H5 => {
337 return Ok(object! {url:e});
338 }
339 Types::MiniJsapi => {
340 println!("alipay.trade.wap.pay:{e:#}");
341 return Ok(e);
342 }
343 Types::App => {}
344 Types::Micropay => {}
345 }
346 Ok(e)
347 }
348 Err(e) => {
349 println!("Err: {e:#}");
350 Err(e)
351 }
352 }
353 }
354
355 fn micropay(&mut self, _channel: &str, auth_code: &str, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, org_openid: &str, _ip: &str) -> Result<JsonValue, String> {
356 let order = object! {
357 out_trade_no:out_trade_no,
358 total_amount:total_fee,
359 subject:description,
360 seller_id:sub_mchid,
361 auth_code:auth_code,
362 scene:"bar_code",
363 operator_id:org_openid,
364 };
365
366 match self.http("alipay.trade.create", object! {"biz_content":order}) {
367 Ok(e) => {
368 Ok(e)
369 }
370 Err(e) => {
371 println!("Err: {e:#}");
372 Err(e)
373 }
374 }
375 }
376
377
378 fn close(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
379 let order = object! {
380 "biz_content"=> object! {
381 out_trade_no:out_trade_no,
382 operator_id:sub_mchid
383 }
384 };
385 match self.http("alipay.trade.close", order) {
386 Ok(_) => {
387 Ok(true.into())
388 }
389 Err(e) => {
390 if e.contains("交易不存在") {
391 return Ok(true.into());
392 }
393 Err(e)
394 }
395 }
396 }
397
398 fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
399 let order = object! {
400 "biz_content"=> object! {
401 out_trade_no:out_trade_no
402 }
403 };
404 match self.http("alipay.trade.query", order) {
405 Ok(e) => {
406 if e.has_key("code") && e["code"].as_str().unwrap() != "10000" {
407 return Err(e["msg"].to_string());
408 }
409 let buyer_open_id = if e.has_key("buyer_open_id") {
410 e["buyer_open_id"].to_string()
411 } else {
412 e["buyer_user_id"].to_string()
413 };
414 let res = PayNotify {
415 trade_type: TradeType::None,
416 out_trade_no: e["out_trade_no"].to_string(),
417 sp_mchid: "".to_string(),
418 sub_mchid: sub_mchid.to_string(),
419 sp_appid: "".to_string(),
420 transaction_id: e["trade_no"].to_string(),
421 success_time: PayNotify::alipay_time(e["send_pay_date"].as_str().unwrap()),
422 sp_openid: buyer_open_id.clone(),
423 sub_openid: buyer_open_id.clone(),
424 total: (e["total_amount"].to_string().parse::<f64>().unwrap_or(0.0)),
425 payer_total: (e["total_amount"].to_string().parse::<f64>().unwrap_or(0.0)),
426 currency: "CNY".to_string(),
427 payer_currency: "CNY".to_string(),
428 trade_state: TradeState::from(e["trade_status"].as_str().unwrap()),
429 };
430 Ok(res.json())
431 }
432 Err(e) => Err(e)
433 }
434 }
435
436 fn pay_micropay_query(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
437 todo!()
438 }
439
440 fn pay_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
441 todo!()
442 }
443
444 fn refund(&mut self, sub_mchid: &str, out_trade_no: &str, transaction_id: &str, out_refund_no: &str, amount: f64, total: f64, _currency: &str) -> Result<JsonValue, String> {
445 let body = object! {
446 "biz_content"=> object! {
447 "trade_no"=>transaction_id,
448 "out_trade_no"=>out_trade_no,
449 "out_request_no"=>out_refund_no,
450 "refund_amount"=>format!("{:.2}",amount),
451 }
452 };
453 match self.http("alipay.trade.refund", body.clone()) {
454 Ok(e) => {
455 if e.has_key("code") && e["code"].as_str().unwrap() != "10000" {
456 return Err(e["msg"].to_string());
457 }
458 let res = RefundNotify {
459 out_trade_no: e["out_trade_no"].to_string(),
460 refund_no: out_refund_no.to_string(),
461 sp_mchid: "".to_string(),
462 sub_mchid: sub_mchid.to_string(),
463 transaction_id: e["trade_no"].to_string(),
464 refund_id: out_refund_no.to_string(),
465 success_time: PayNotify::alipay_time(e["gmt_refund_pay"].as_str().unwrap()),
466 total,
467 refund: e["refund_fee"].to_string().parse::<f64>().unwrap(),
468 payer_total: e["refund_fee"].to_string().parse::<f64>().unwrap(),
469 payer_refund: e["send_back_fee"].to_string().parse::<f64>().unwrap(),
470 status: RefundStatus::from(e["fund_change"].as_str().unwrap()),
471 };
472 Ok(res.json())
473 }
474 Err(e) => Err(e)
475 }
476 }
477
478 fn micropay_refund(&mut self, _sub_mchid: &str, _out_trade_no: &str, _transaction_id: &str, _out_refund_no: &str, _amount: f64, _total: f64, _currency: &str, _refund_text: &str) -> Result<JsonValue, String> {
479 todo!()
480 }
481
482 fn refund_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
483 todo!()
484 }
485
486 fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
487 let body = object! {
488 "biz_content"=> object! {
489 "out_request_no"=>out_refund_no,
490 "trade_no"=>trade_no,
491 }
492 };
493 match self.http("alipay.trade.fastpay.refund.query", body.clone()) {
494 Ok(e) => {
495 if e.has_key("code") && e["code"].as_str().unwrap() != "10000" {
496 return Err(e["msg"].to_string());
497 }
498 let res = RefundNotify {
499 out_trade_no: e["out_trade_no"].to_string(),
500 refund_no: e["out_request_no"].to_string(),
501 sp_mchid: "".to_string(),
502 sub_mchid: sub_mchid.to_string(),
503 transaction_id: e["trade_no"].to_string(),
504 refund_id: e["out_request_no"].to_string(),
505 success_time: Local::now().timestamp(),
506 total: e["total_amount"].to_string().parse::<f64>().unwrap(),
507 payer_total: e["total_amount"].to_string().parse::<f64>().unwrap(),
508 refund: e["refund_amount"].to_string().parse::<f64>().unwrap(),
509 payer_refund: e["refund_amount"].to_string().parse::<f64>().unwrap(),
510 status: RefundStatus::from(e["refund_status"].as_str().unwrap()),
511 };
512 Ok(res.json())
513 }
514 Err(e) => Err(e)
515 }
516 }
517
518 fn incoming(&mut self, _business_code: &str, _contact_info: JsonValue, _subject_info: JsonValue, _business_info: JsonValue, _settlement_info: JsonValue, _bank_account_info: JsonValue) -> Result<JsonValue, String> {
519 todo!()
520 }
521}