pythonsquare

How to retrieve customer id from create customer method in Square using Python


I'm creating a customer in square and getting the results as follows. What I need is to get the id of customer.

My code :

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)

And this is the output:

<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"}
               }
              ]>

Solution

  • Are you using this library ? https://github.com/square/square-python-sdk/blob/master/square/http/api_response.py

    if yes result is an array and APiResponse object.

    so first you should do that : result = result.body then to get the list of customers: result['customers'], then each of those have an id

    Ps : You have exemple in the 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}")