As part of some on the side work I’m doing for Hanafins, I needed to syncronise products added in Shopify with Telecom’s Ferrit ecommerce system. To do this, you need to be able to export all the products out of Shopify. This isn’t easy as the Shopify API isn’t ready yet.
In the meantime, use the script below to emulate a browser logging in and request the products.xml file.
The Code
Firstly you’ll want to install the ‘mechanize’ gem.
sudo gem install mechanize --include-dependencies
Is this example we’re using a Shopify model and a download_xml method.
require 'mechanize' # Required to login and download the products feed
# This model handles the downloading of the Shopify XML feed
class Shopify < ActiveRecord::Base
URL = "http://yourstore.myshopify.com"
LOGIN = "you@youremail.com"
PASSWORD = "yourpassword"
# Download the XML feed from Shopify
def download_xml
# Request the login page
agent = WWW::Mechanize.new
page = agent.get("#{URL}/admin/auth/login")
# Input the login creditionals into the form
form = page.forms.first
form.login = LOGIN
form.password = PASSWORD
page = agent.submit(form, form.buttons.first)
# Request all the products in the store. Stops at 10,000 products.
page = agent.get("#{URL}/admin/products.xml?limit=10000")
page.body
end
end
And that’s it! So now in your controller you could go:
products_xml = Shopify.new.download_xml
render :text => products_xml
And you would get all the products outputted in XML from your Shopify store.