Skip to main content

casdoor_rust_sdk/
order_pay.rs

1// Copyright 2026 The Casdoor Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use serde::Serialize;
16
17use crate::client::{Client, PostBody};
18use crate::error::Result;
19use crate::order::{Order, ProductInfo};
20use crate::payment::Payment;
21
22#[derive(Serialize)]
23#[serde(rename_all = "camelCase")]
24struct PlaceOrderRequest<'a> {
25    product_infos: &'a [ProductInfo],
26}
27
28impl Client {
29    /// Place an order for the given products. `user_name` can be empty to place the order
30    /// for the user that the client is authenticated as.
31    pub async fn place_order(
32        &self,
33        product_infos: &[ProductInfo],
34        user_name: &str,
35    ) -> Result<Order> {
36        let mut query = vec![("owner", self.config.organization_name.as_str())];
37        if !user_name.is_empty() {
38            query.push(("userName", user_name));
39        }
40
41        let post_bytes = serde_json::to_vec(&PlaceOrderRequest { product_infos })?;
42        let response = self
43            .do_post("place-order", &query, PostBody::Raw(post_bytes))
44            .await?;
45
46        Ok(serde_json::from_value(response.data)?)
47    }
48
49    /// Pay an order with a payment provider, the returned payment holds the `pay_url` the
50    /// user has to be redirected to.
51    pub async fn pay_order(&self, order_name: &str, provider_name: &str) -> Result<Payment> {
52        let response = self
53            .do_post(
54                "pay-order",
55                &[
56                    ("id", &self.get_id(order_name)),
57                    ("providerName", provider_name),
58                ],
59                PostBody::Raw(Vec::new()),
60            )
61            .await?;
62
63        Ok(serde_json::from_value(response.data)?)
64    }
65
66    /// Place an order of one product, kept for compatibility with the old `buy-product`
67    /// API.
68    pub async fn buy_product(&self, name: &str, user_name: &str) -> Result<Order> {
69        let product_info = ProductInfo {
70            name: name.to_string(),
71            quantity: 1,
72            ..Default::default()
73        };
74
75        self.place_order(&[product_info], user_name).await
76    }
77}