如何使用Python在Square中从创建客户方法中检索客户ID

问题描述

我正在创建一个正方形的客户,并得到如下结果。我需要获取客户ID。

我的代码

from square.client import Client

client = Client(
    access_token=settings.SQUARE_ACCESS_TOKEN,environment=settings.SQUARE_ENVIRONMENT,)
api_customers = client.customers
request_body = {'idempotency_key': idempotency_key,'given_name': name,'company_name': company,'phone_number':phone}
result = api_customers.create_customer(request_body)

这是输出

<ApiResponse [{"customer": 
                {"id": "F8M9KDHWPMYGK2108RMQVQ6FHC","created_at": "2020-10-22T09:14:50.159Z","updated_at": "2020-10-22T09:14:50Z","given_name": "mkv5","phone_number": "900000066666","company_name": "codesvera","preferences": {"email_unsubscribed": false},"creation_source": "THIRD_PARTY"}
               }
              ]>

解决方法

您正在使用此库吗? https://github.com/square/square-python-sdk/blob/master/square/http/api_response.py

如果是,则结果为数组和APiResponse对象。

所以首先您应该这样做:result = result.body 然后获取ID:result['customer']['id']

Ps:您在github doc中有一个例子: https://github.com/square/square-python-sdk

# Initialize the customer count
total_customers = 0
# Initialize the cursor with an empty string since we are 
# calling list_customers for the first time
cursor = ""
# Count the total number of customers using the list_customers method
while True:
    # Call list_customers method to get all customers in this Square account
    result = api_customers.list_customers(cursor)
    if result.is_success():
        # If any customers are returned,the body property 
        # is a list with the name customers.
        # If there are no customers,APIResponse returns
        # an empty dictionary.
        if result.body:
            customers = result.body['customers']
            total_customers += len(customers)
            # Get the cursor if it exists in the result else set it to None
            cursor = result.body.get('cursor',None)
            print(f"cursor: {cursor}")
        else:
            print("No customers.")
            break
    # Call the error method to see if the call failed
    elif result.is_error():
        print(f"Errors: {result.errors}")
        break
    
    # If there is no cursor,we are at the end of the list.
    if cursor == None:
        break

print(f"Total customers: {total_customers}")