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 NativeRequest {
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 NativeResponse {
pub code_url: String,
}
#[allow(dead_code)]
pub struct NativeService {
config: Arc<WxPayConfig>,
http_client: Arc<dyn HttpClient>,
signer: Arc<dyn Signer>,
transport: ServiceTransport,
}
impl NativeService {
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: &NativeRequest) -> WxPayResult<NativeResponse> {
let body = serde_json::to_string(request)?;
self.transport
.request(
HttpMethod::Post,
"/v3/pay/transactions/native",
Some(&body),
"payments.native.create_order",
)
.await
}
pub async fn prepay(&self, request: &NativeRequest) -> WxPayResult<NativeResponse> {
self.create_order(request).await
}
}
impl std::fmt::Debug for NativeService {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NativeService").finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_native_request_serialization() {
let request = NativeRequest {
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_native_response_deserialization() {
let json = r#"{"code_url":"weixin://wxpay/bizpayurl?pr=xxxxx"}"#;
let response: NativeResponse = serde_json::from_str(json).unwrap();
assert!(response.code_url.starts_with("weixin://wxpay/bizpayurl"));
}
}