use serde::{Deserialize, Serialize};
use std::sync::Arc;
use crate::auth::Signer;
use crate::config::WxPayConfig;
use crate::error::WxPayResult;
use crate::http::{HttpClient, HttpMethod};
use crate::services::payments::jsapi::Amount;
use crate::services::transport::{ServiceTransport, TransportObserver};
#[derive(Debug, Clone, Serialize)]
pub struct AppRequest {
pub appid: String,
pub mchid: String,
pub description: String,
pub out_trade_no: String,
pub amount: Option<Amount>,
pub notify_url: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AppResponse {
pub prepay_id: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct AppPayParams {
pub appid: String,
pub partnerid: String,
pub prepayid: String,
pub package: String,
pub noncestr: String,
pub timestamp: String,
pub sign: String,
}
#[allow(dead_code)]
pub struct AppService {
config: Arc<WxPayConfig>,
http_client: Arc<dyn HttpClient>,
signer: Arc<dyn Signer>,
transport: ServiceTransport,
}
impl AppService {
pub fn new(
config: Arc<WxPayConfig>,
http_client: Arc<dyn HttpClient>,
signer: Arc<dyn Signer>,
) -> Self {
Self::new_with_observer(config.clone(), http_client.clone(), signer.clone(), None)
}
pub fn new_with_observer(
config: Arc<WxPayConfig>,
http_client: Arc<dyn HttpClient>,
signer: Arc<dyn Signer>,
transport_observer: Option<Arc<dyn TransportObserver>>,
) -> Self {
Self {
config: config.clone(),
http_client: http_client.clone(),
signer: signer.clone(),
transport: ServiceTransport::new_with_observer(
config,
http_client,
signer,
transport_observer,
),
}
}
pub async fn create_order(&self, request: &AppRequest) -> WxPayResult<AppResponse> {
let body = serde_json::to_string(request)?;
self.transport
.request(
HttpMethod::Post,
"/v3/pay/transactions/app",
Some(&body),
"payments.app.create_order",
)
.await
}
pub async fn prepay(&self, request: &AppRequest) -> WxPayResult<AppResponse> {
self.create_order(request).await
}
pub async fn generate_pay_params(&self, prepay_id: &str) -> WxPayResult<AppPayParams> {
let timestamp = crate::utils::timestamp::get_timestamp();
let nonce = crate::utils::nonce::generate_nonce();
let message = format!("{}\n{}\nprepay_id={}\n", timestamp, nonce, prepay_id);
let signature = self.signer.sign(&message).await?;
Ok(AppPayParams {
appid: self.config.app_id.clone(),
partnerid: self.config.merchant_id.clone(),
prepayid: prepay_id.to_string(),
package: "Sign=WXPay".to_string(),
noncestr: nonce,
timestamp: timestamp.to_string(),
sign: signature,
})
}
}
impl std::fmt::Debug for AppService {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AppService").finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_app_request_serialization() {
let request = AppRequest {
appid: "wx88888888".to_string(),
mchid: "1900000109".to_string(),
description: "测试商品".to_string(),
out_trade_no: "test_trade_no_123".to_string(),
amount: Some(Amount {
total: 100,
currency: Some("CNY".to_string()),
}),
notify_url: None,
};
let json = serde_json::to_string(&request).unwrap();
assert!(json.contains("wx88888888"));
assert!(json.contains("1900000109"));
}
#[test]
fn test_app_response_deserialization() {
let json = r#"{"prepay_id":"wx201410272009395522657a690ac89ed300"}"#;
let response: AppResponse = serde_json::from_str(json).unwrap();
assert_eq!(response.prepay_id, "wx201410272009395522657a690ac89ed300");
}
}