def create(self, number_orders): # these lists will be added to a data file after creation orders_created = [] customers_created = [] print("Total Products Sampling From: {}\n".format(len(self.products))) for counter in range(number_orders): print("Generating Order: {0}".format(str(counter + 1))) new_order = shopify.Order().create(self.generate_data(self)) if new_order.errors: # something went wrong! # TODO: we need to loop over our error messages and print them for message in new_order.errors.full_messages(): print("[ERROR] {0}".format(message)) return orders_created.append(str(new_order.id)) customers_created.append(str(new_order.customer.id)) # Write our created data to file. This is required for simple deletion later using this same tool. # If these files do not exist, you will have to delete the data manually through the Shopify dashboard. with open('stdg-orders.csv', mode='a') as order_file: order_file.write('\n'.join(orders_created) + '\n') with open('stdg-customers.csv', mode='a') as customers_file: customers_file.write('\n'.join(customers_created) + '\n') return
def create_order_view(cls): json = cls._get_json_from_request() invoice = json['data']['object'] shopify.ShopifyResource.set_site( "https://%s:%[email protected]/admin" % (app.config['SHOPIFY_API_KEY'], app.config['SHOPIFY_PASSWORD'])) order = shopify.Order() order.customer = { 'id': invoice['lines']['data'][0]['metadata']['customer_id'] } order.send_receipt = True order.use_customer_default_address = True order.line_items = [] for line in invoice['lines']['data']: order.line_items.append({ 'title': line['plan']['name'].split(' - ')[0], 'product_id': line['plan']['id'].split('-')[0], 'quantity': line['quantity'], 'price': str(line['amount'] / 100) }) order.note_attributes = [{'invoice_id': invoice['id']}] order.source_name = 'subscriptions' order.save() return cls._format_response({})
def create_an_order(**kwargs): session = shopify.Session(shop_url, api_version, access_token) shopify.ShopifyResource.activate_session(session) variants = [] new_order = shopify.Order() for key, value in kwargs.items(): setattr(new_order, key, value) result = new_order.save() print(result) print(new_order.id) print(new_order.to_dict())
def test_should_be_able_to_add_note_attributes_to_an_order(self): order = shopify.Order() order.note_attributes = [] order.note_attributes.append(shopify.NoteAttribute({'name': "color", 'value': "blue"})) order_xml = xml_to_dict(order.to_xml()) note_attributes = order_xml["order"]["note_attributes"] self.assertTrue(isinstance(note_attributes, list)) attribute = note_attributes[0] self.assertEqual("color", attribute["name"]) self.assertEqual("blue", attribute["value"])
def test_should_be_loaded_correctly_from_order_xml(self): order_xml = """<?xml version="1.0" encoding="UTF-8"?> <order> <note-attributes type="array"> <note-attribute> <name>size</name> <value>large</value> </note-attribute> </note-attributes> </order>""" order = shopify.Order(xml_to_dict(order_xml)["order"]) self.assertEqual(1, len(order.note_attributes)) note_attribute = order.note_attributes[0] self.assertEqual("size", note_attribute.name) self.assertEqual("large", note_attribute.value)
def post(self, request, *args, **kwargs): result = dict() if request.user.is_authenticated: s = serializers.OrderCartSerializer(data=request.data) if s.is_valid(): order = shopify.Order() order.email = request.user.email order.fulfillment_status = "fulfilled" order.send_receipt = True order.send_fulfillment_receipt = False order.line_items = [] carts = models.Cart.objects.filter(user=request.user, is_paid=False) total_price = 0 for cart in carts: cart.is_paid = True product = shopify.Product.find(cart.product) for v in product.variants: if v.id == int(cart.varient): order.line_items.append({ "variant_id": v.id, "quantity": 1 }) shopify.InventoryLevel.set( location[0].id, v.inventory_item_id, v.inventory_quantity - 1) success = True total_price = total_price + float(v.price) cart.save() success = order.save() models.Orders(total_amount=total_price, order_id=order.id, user=request.user).save() result['status'] = success return Response(result, template_name='orders.html') else: result['status'] = False result['error'] = "Bad Request" return Response(result) else: result['status'] = False result['error'] = "Unauthorized" return Response(result)
def create_order(first_name, last_name, phone, town, address1, user_id): order = shopify.Order() shipping_address = shopify.ShippingAddress() shipping_address.first_name = first_name shipping_address.last_name = last_name shipping_address.city = town shipping_address.address1 = address1 shipping_address.phone = phone shipping_address.country = "Ukraine" billing_address = shopify.BillingAddress() billing_address.first_name = first_name billing_address.last_name = last_name billing_address.city = town billing_address.address1 = address1 billing_address.phone = phone billing_address.country = "Ukraine" customer = shopify.Customer.find(user_id) item = shopify.LineItem() item.variant_id = 12438658154559 item.quantity = 1 order.shipping_address = shipping_address order.billing_address = billing_address order.line_items = [item] order.gateway = "Оплата при отриманні" order.payment_gateway_names = ["Оплата при отриманні"] order.customer = customer order.contact_email = customer.email #d["user_id"] = 686081769535 order.email = customer.email order.fulfillment_status = 'fulfilled' order.send_receipt = False order.send_fulfillment_receipt = False order.suppress_notifications = False order.save() return order.order_status_url
def update_shopify(self): pool = Pool() Shipment = pool.get('stock.shipment.out') Address = pool.get('party.address') Party = pool.get('party.party') PartyIdentifier = pool.get('party.identifier') Move = pool.get('stock.move') Product = pool.get('product.product') Template = pool.get('product.template') Country = pool.get('country.country') Subdivision = pool.get('country.subdivision') ProductUOM = pool.get('product.uom') ModelData = pool.get('ir.model.data') url = 'https://{}:{}@{}'.format(self.api_key, self.api_password, self.url) shopify.ShopifyResource.set_site(url) if self.name != 'TestShop': # real update orders_list = self.get_shopify_orders() else: # test update # loads order_1.json into orders list path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tests/order_1.json') with open(path) as json_file: order_json = json.load(json_file)['order'] order = shopify.Order(order_json) orders_list = [order] unit_uom = ProductUOM(ModelData.get_id('product', 'uom_unit')) shipments_to_save = [] for order in orders_list: existent_shipment = Shipment.search([('shop_order_id', '=', order.id), ('shop', '=', self.id)]) if existent_shipment: continue # In some cases (ie, the customer will pick the product from the # warehouse) the shipping_address may not exist shipping_address = getattr(order, 'shipping_address', None) if hasattr(order, 'customer') and order.customer: customer = order.customer else: raise UserError( gettext('stock_shipment_ecommerce.missing_customer', order=order.order_number, shop=self.name)) parties = Party.search([('identifiers.code', '=', customer.id), ('identifiers.type', '=', 'shop')], limit=1) if not parties and shipping_address: party = Party() party.name = shipping_address.name party.shop = self party.save() identifier = PartyIdentifier() identifier.party = party identifier.type = 'shop' identifier.code = customer.id identifier.save() elif not shipping_address: party = self.party else: party, = parties if party.name != shipping_address.name: party.name = shipping_address.name party.save() if shipping_address: address_exist = Address.search([ ('party', '=', party), ('street', '=', shipping_address.address1), ('postal_code', '=', shipping_address.zip) ]) if address_exist: address = address_exist[0] else: address = Address() address.street = shipping_address.address1 address.city = shipping_address.city countries = Country.search( [('code', '=', shipping_address.country_code)], limit=1) if not countries: raise UserError( gettext( 'stock_shipment_ecommerce.country_not_found', order=order.order_number, shop=self.name)) address.country, = countries if shipping_address.province_code: if '-' not in shipping_address.province_code: sub_code = (address.country.code + '-' + shipping_address.province_code) else: sub_code = shipping_address.province_code subdivisions = Subdivision.search( [('code', '=', sub_code)], limit=1) if not subdivisions: subdivisions = Subdivision.search( [('code', 'ilike', sub_code + '%')], limit=1) else: address.subdivision, = subdivisions address.party = party address.postal_code = shipping_address.zip address.delivery = True address.save() else: addresses = Address.search([('party', '=', party)]) if addresses: address = addresses[0] else: raise UserError( gettext('stock_shipment_ecommerce.no_pickup_address', party=party.rec_name, order=order.order_number, shop=self.name)) shipment = Shipment() shipment.sale_date = datetime.strptime(order.created_at[0:10], "%Y-%m-%d").date() shipment.customer = party shipment.delivery_address = address shipment.origin_party = self.party shipment.reference = order.order_number shipment.shop_order_id = order.id shipment.shop = self.id shipment.warehouse = self.warehouse shipment.state = 'draft' shipment.json_order = order.to_json() shipment.customer_phone_numbers = get_customer_phone_numbers(order) shipment.comment = order.note or '' attributes = [] for attribute in order.note_attributes: attributes += list(attribute.to_dict().values()) shipment.comment += '\n'.join(attribute.to_dict().values()) shipments_to_save.append(shipment) moves = [] for line in order.line_items: products = Product.search([ ('template.party', '=', self.party), ('party_code', '=', line.sku), ], limit=1) if not products: if not self.create_products: raise UserError( gettext('stock_shipment_ecommerce.missing_product', product=line.sku, order=order.order_number, shop=self.name)) template = Template() template.name = line.title template.type = 'goods' template.default_uom = unit_uom template.party = self.party template.list_price = 0 template.save() product = Product() product.code = line.sku product.cost_price = 0 product.template = template if not line.sku: raise UserError( gettext('stock_shipment_ecommerce.no_product_sku', product=template.name, order=order.order_number, shop=self.name)) product.party_code = line.sku product.save() products = [product] product, = products move = Move() move.shipment = shipment move.from_location = self.warehouse.output_location move.to_location = self.party.customer_location move.quantity = line.quantity move.product = product move.uom = product.default_uom move.unit_price = product.list_price moves.append(move) shipment.outgoing_moves = tuple(moves) Shipment.save(shipments_to_save) Shipment.wait(shipments_to_save)
import shopify API_KEY = 'XXXXX' PASSWORD = '******' SHOP_NAME = 'XXXXX' shop_url = "https://XXXXX.com/admin" % (API_KEY, PASSWORD, SHOP_NAME) shopify.ShopifyResource.set_site(shop_url) shop = shopify.Shop.current() order = shopify.Order() num = order.count() if num == 1: print "There is %s order currently in your %s shopify store" % (num, SHOP_NAME) else: print "There are %s orders currently in your %s shopify store" % ( num, SHOP_NAME)
def __init__(self, api_key, password, shop_name): shop_url = "https://%s:%s@%s.myshopify.com/admin" % (api_key, password, shop_name) shopify.ShopifyResource.set_site(shop_url) self.order = shopify.Order()