首页 > 编程问答 >使用 Python 中的 Square API 检索客户 ID

使用 Python 中的 Square API 检索客户 ID

时间:2024-07-25 11:54:45浏览次数:7  
标签:python square

我正在为 Square 开发一个客户创建表单,它将创建一个客户,然后立即检索他们的 ID 以在程序中进一步使用。但是,我不知道如何使用 API 来过滤使用 list_customers 命令返回的数据。

我找到了这篇文章: How toretrieve customer id from create customer method in Square using Python 这是四年前问的同样的事情,我不明白他们收到的答案。他们说“所以首先你应该这样做:result = result.body,然后获取ID:result['customer']['id']”,但我不知道如何将其实现到我的代码中。

编辑: 我现在收到错误:

“TypeError:列表索引必须是整数或切片,而不是 str”。这 返回的 ApiObject 格式为 <ApiResponse {"customers": [{"id": “Z6MNDFH4DQCW09ZZAVX6CX9H2G”,“创建于”: “2024-06-19T19:21:57.423Z”,“updated_at”:“2024-07-23T20:48:07Z”...>


出现 TypeError: list indices must be integers or slices, not str 错误的原因是, list_customers API 调用返回的是客户列表,而不是单个客户。虽然可能希望在创建客户后立即获取该客户的 ID,但 API 响应包含的格式不同。

以下是如何在使用 Square API 创建客户后获取客户 ID 的方法:

import square

# 初始化 Square 客户端
location_id = 'YOUR_LOCATION_ID'
access_token = 'YOUR_ACCESS_TOKEN'
client = square.Client(access_token=access_token, environment='sandbox')

# 创建客户数据
customer_data = {
    'given_name': 'John',
    'family_name': 'Doe',
    'email_address': '[email protected]',
    'phone_number': '555-123-4567'
}

# 创建客户请求
try:
    result = client.customers.create_customer(body=customer_data)
    # 从结果中直接获取客户 ID
    customer_id = result.customer.id
    print("新创建的客户 ID 为:", customer_id)
except square.ApiException as e:
    print("出现错误:", e.status_code)
    print(e.response.text)

在此代码中:

  1. 创建客户:
  2. 使用 client.customers.create_customer(body=customer_data) 创建一个新客户。
  3. result 将保存对 create_customer 调用的响应。

  4. 从结果中检索客户 ID:

  5. 成功创建客户后, result 对象将包含已创建客户的信息。
  6. 通过访问 result.customer.id 直接访问客户 ID。

  7. 处理错误:

  8. try...except 块用于捕获在 API 调用过程中可能发生的任何 square.ApiException 。这确保了如果创建客户出现问题(例如重复的电子邮件地址),则脚本将捕获错误而不是崩溃。

此代码展示了一种在成功执行 create_customer 调用后立即检索客户 ID 的更直接方法。

请记住将 YOUR_LOCATION_ID YOUR_ACCESS_TOKEN 替换为的实际凭据。

标签:python,square
From: 78790176

相关文章