简体   繁体   中英

How to add a customer in Shopify API?

When I try to add a new customer with the following code:

new_customer = shopify.Customer()
new_customer.first_name = "andres"
new_customer.last_name = "cepeda"
success = new_customer.save()

And it works. However when I tried to add another fields such a address or company,

new_customer = shopify.Customer()
new_customer.first_name = "andres"
new_customer.last_name = "cepeda"
new_customer.company = "my company"
new_customer.address = "cll 25 - 27"
success = new_customer.save()

It didn't work.

Try with this.

custo = shopify.Customer()
      custo.first_name = "andres"
      custo.last_name = "cepeda"
      custo.addresses = [{"address1": "123 Oak st", "city": "Ottawa", "phone": "9876543210"}]
      custo.save()

Hope this helps.

There are two issues with the OP's code and neither of the answers above address both issues here so I'll add my answer.

First issue: In order to add the address to the new_customer, you have to use "addresses" property, not "address". He was missing the "es" at the end (plural). This is because the addresses property is a list. Even if you only want to add 1 address, you must include it in list brackets as shown below.

new_customer = shopify.Customer()
  new_customer.first_name = "andres"
  new_customer.last_name = "cepeda"
  new_customer.addresses = [{"address1": "123 Oak st", "city": "Ottawa", "phone": "9876543210", "company": "Apple"}]
  new_customer.default_address = {"address1": "123 Oak st", "city": "Ottawa", "phone": "9876543210", "company": "Apple"}
  new_customer.save()

You can set the default address by using a dictionary directly. This is because this field is always going to be only 1 address so there is no need to use list format (and will error out if you try).

Second Issue: The second issue is that the OP is trying to set "company" field directly on the Customer object (new_customer). The company field is part of the address, not the customer directly. As shown in my example above, include company as one of the address fields and it will work.

See docs for reference: https://help.shopify.com/en/api/reference/customers/customer#what-you-can-do-with-customer

Try:

address = { address1: 'Some address', city: 'Ottawa', province: 'ON', zip: 'K1P 0C2' }

new.customer.addresses = [address]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM