导入
创建订单
按照逐步说明,使用 Square API 创建、克隆或计算订单。
CreateOrder 端点用于创建一个订单,其中包含有关商品及购买时应用的设置信息。
该端点需要一个 order 对象作为请求参数。此对象可能包括商品项、折扣和税费。CreateOrder 端点唯一必需的参数是 location_id。以下小工具展示了创建订单所需的最简代码。请注意,这段代码将创建一个空订单。
注意: 以下代码提取订单 ID 并将其保存在名为
EMPTY_ORDER_ID的键中,供后续使用。
1result = client.orders.create_order( 2 body = { 3 "order": { 4 "location_id": "{{LOCATION_ID}}" 5 } 6 } 7) 8 9if result.is_success(): 10 pprint(result.body) 11elif result.is_error(): 12 pprint(result.errors)
除了 location_id 外,order 还可以包含其他多个字段,例如 reference_id、line_items、taxes 和 discounts。此外,还可以传递一个 idempotency_key,用于唯一标识我们已创建的订单。
让我们使用这些字段创建另一个订单,并观察响应结果,以了解 Order 对象的具体结构。
注意: 以下代码提取订单 ID 并将其保存在名为
ORDER_ID的键中。
1random_string = ''.join(random.choice(string.ascii_letters) for i in range(40)) 2 3result = client.orders.create_order( 4 body = { 5 "order": { 6 "location_id": "{{LOCATION_ID}}", 7 "reference_id": "my-order-001", 8 "line_items": [{ 9 "name": "纽约牛排", 10 "quantity": "1", 11 "base_price_money": { 12 "amount": 1599, 13 "currency": "USD" 14 } 15 }], 16 "taxes": [{ 17 "uid": "state-sales-tax", 18 "name": "州销售税", 19 "percentage": "9", 20 "scope": "ORDER" 21 }], 22 "discounts": [{ 23 "uid": "labor-day-sale", 24 "name": "劳动节促销", 25 "percentage": "5", 26 "scope": "ORDER" 27 }, 28 { 29 "uid": "one-dollar-off", 30 "name": "促销 - 减 $1.00", 31 "amount_money": { 32 "amount": 100, 33 "currency": "USD" 34 }, 35 "scope": "LINE_ITEM" 36 }] 37 }, 38 "idempotency_key": random_string 39 } 40) 41 42if result.is_success(): 43 pprint(result.body) 44elif result.is_error(): 45 pprint(result.errors)
克隆订单
CloneOrder 端点通过复制现有订单来创建一个新的订单,新订单的状态为 DRAFT。仅核心字段(商品项、税费和折扣)从原订单复制到克隆订单中。以下代码将克隆我们刚刚创建的订单。响应中的 state 字段显示克隆后的订单处于 DRAFT 状态。
1result = client.orders.clone_order( 2 body = { 3 "order_id": "{{ORDER_ID}}" 4 } 5) 6 7if result.is_success(): 8 pprint(result.body) 9elif result.is_error(): 10 pprint(result.errors)
计算订单
在电商网站上,我们经常需要在确认前预估订单金额。Square 的 CalculateOrder 端点允许我们实现这一功能。它可以在不实际创建订单的情况下,预览订单的价格。
让我们使用以下代码计算一个订单。我们可以通过响应中的 total_money 字段获取订单金额的估算值。
1result = client.orders.calculate_order( 2 body = { 3 "order": { 4 "location_id": "{{LOCATION_ID}}", 5 "line_items": [{ 6 "name": "商品 1", 7 "quantity": "1", 8 "base_price_money": { 9 "amount": 500, 10 "currency": "USD" 11 } 12 }, 13 { 14 "name": "商品 2", 15 "quantity": "2", 16 "base_price_money": { 17 "amount": 300, 18 "currency": "USD" 19 } 20 }], 21 "discounts": [{ 22 "name": "50% 折扣", 23 "percentage": "50", 24 "scope": "ORDER" 25 }] 26 } 27 } 28) 29 30if result.is_success(): 31 pprint(result.body) 32elif result.is_error(): 33 pprint(result.errors)