shopify_api.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. require 'active_resource'
  2. require 'active_support/core_ext/class/attribute_accessors'
  3. require 'digest/md5'
  4. module ShopifyAPI
  5. METAFIELD_ENABLED_CLASSES = %w( Order Product CustomCollection SmartCollection Page Blog Article Variant)
  6. EVENT_ENABLED_CLASSES = %w( Order Product CustomCollection SmartCollection Page Blog Article )
  7. module Countable
  8. def count(options = {})
  9. Integer(get(:count, options))
  10. end
  11. end
  12. module Metafields
  13. def metafields
  14. Metafield.find(:all, :params => {:resource => self.class.collection_name, :resource_id => id})
  15. end
  16. def add_metafield(metafield)
  17. raise ArgumentError, "You can only add metafields to resource that has been saved" if new?
  18. metafield.prefix_options = {
  19. :resource => self.class.collection_name,
  20. :resource_id => id
  21. }
  22. metafield.save
  23. metafield
  24. end
  25. end
  26. module Events
  27. def events
  28. Event.find(:all, :params => {:resource => self.class.collection_name, :resource_id => id})
  29. end
  30. end
  31. #
  32. # The Shopify API authenticates each call via HTTP Authentication, using
  33. # * the application's API key as the username, and
  34. # * a hex digest of the application's shared secret and an
  35. # authentication token as the password.
  36. #
  37. # Generation & acquisition of the beforementioned looks like this:
  38. #
  39. # 0. Developer (that's you) registers Application (and provides a
  40. # callback url) and receives an API key and a shared secret
  41. #
  42. # 1. User visits Application and are told they need to authenticate the
  43. # application first for read/write permission to their data (needs to
  44. # happen only once). User is asked for their shop url.
  45. #
  46. # 2. Application redirects to Shopify : GET <user's shop url>/admin/api/auth?api_key=<API key>
  47. # (See Session#create_permission_url)
  48. #
  49. # 3. User logs-in to Shopify, approves application permission request
  50. #
  51. # 4. Shopify redirects to the Application's callback url (provided during
  52. # registration), including the shop's name, and an authentication token in the parameters:
  53. # GET client.com/customers?shop=snake-oil.myshopify.com&t=a94a110d86d2452eb3e2af4cfb8a3828
  54. #
  55. # 5. Authentication password computed using the shared secret and the
  56. # authentication token (see Session#computed_password)
  57. #
  58. # 6. Profit!
  59. # (API calls can now authenticate through HTTP using the API key, and
  60. # computed password)
  61. #
  62. # LoginController and ShopifyLoginProtection use the Session class to set Shopify::Base.site
  63. # so that all API calls are authorized transparently and end up just looking like this:
  64. #
  65. # # get 3 products
  66. # @products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
  67. #
  68. # # get latest 3 orders
  69. # @orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
  70. #
  71. # As an example of what your LoginController should look like, take a look
  72. # at the following:
  73. #
  74. # class LoginController < ApplicationController
  75. # def index
  76. # # Ask user for their #{shop}.myshopify.com address
  77. # end
  78. #
  79. # def authenticate
  80. # redirect_to ShopifyAPI::Session.new(params[:shop]).create_permission_url
  81. # end
  82. #
  83. # # Shopify redirects the logged-in user back to this action along with
  84. # # the authorization token t.
  85. # #
  86. # # This token is later combined with the developer's shared secret to form
  87. # # the password used to call API methods.
  88. # def finalize
  89. # shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
  90. # if shopify_session.valid?
  91. # session[:shopify] = shopify_session
  92. # flash[:notice] = "Logged in to shopify store."
  93. #
  94. # return_address = session[:return_to] || '/home'
  95. # session[:return_to] = nil
  96. # redirect_to return_address
  97. # else
  98. # flash[:error] = "Could not log in to Shopify store."
  99. # redirect_to :action => 'index'
  100. # end
  101. # end
  102. #
  103. # def logout
  104. # session[:shopify] = nil
  105. # flash[:notice] = "Successfully logged out."
  106. #
  107. # redirect_to :action => 'index'
  108. # end
  109. # end
  110. #
  111. class Session
  112. cattr_accessor :api_key
  113. cattr_accessor :secret
  114. cattr_accessor :protocol
  115. self.protocol = 'https'
  116. attr_accessor :url, :token, :name
  117. def self.setup(params)
  118. params.each { |k,value| send("#{k}=", value) }
  119. end
  120. def initialize(url, token = nil, params = nil)
  121. self.url, self.token = url, token
  122. if params
  123. unless self.class.validate_signature(params) && params[:timestamp].to_i > 24.hours.ago.utc.to_i
  124. raise "Invalid Signature: Possible malicious login"
  125. end
  126. end
  127. self.class.prepare_url(self.url)
  128. end
  129. def shop
  130. Shop.current
  131. end
  132. def create_permission_url
  133. return nil if url.blank? || api_key.blank?
  134. "http://#{url}/admin/api/auth?api_key=#{api_key}"
  135. end
  136. # Used by ActiveResource::Base to make all non-authentication API calls
  137. #
  138. # (ShopifyAPI::Base.site set in ShopifyLoginProtection#shopify_session)
  139. def site
  140. "#{protocol}://#{api_key}:#{computed_password}@#{url}/admin"
  141. end
  142. def valid?
  143. url.present? && token.present?
  144. end
  145. private
  146. # The secret is computed by taking the shared_secret which we got when
  147. # registring this third party application and concating the request_to it,
  148. # and then calculating a MD5 hexdigest.
  149. def computed_password
  150. Digest::MD5.hexdigest(secret + token.to_s)
  151. end
  152. def self.prepare_url(url)
  153. return nil if url.blank?
  154. url.gsub!(/https?:\/\//, '') # remove http:// or https://
  155. url.concat(".myshopify.com") unless url.include?('.') # extend url to myshopify.com if no host is given
  156. end
  157. def self.validate_signature(params)
  158. return false unless signature = params[:signature]
  159. sorted_params = params.except(:signature, :action, :controller).collect{|k,v|"#{k}=#{v}"}.sort.join
  160. Digest::MD5.hexdigest(secret + sorted_params) == signature
  161. end
  162. end
  163. class Base < ActiveResource::Base
  164. extend Countable
  165. end
  166. # Shop object. Use Shop.current to receive
  167. # the shop.
  168. class Shop < Base
  169. def self.current
  170. find(:one, :from => "/admin/shop.#{format.extension}")
  171. end
  172. def metafields
  173. Metafield.find(:all)
  174. end
  175. def add_metafield(metafield)
  176. raise ArgumentError, "You can only add metafields to resource that has been saved" if new?
  177. metafield.save
  178. metafield
  179. end
  180. def events
  181. Event.find(:all)
  182. end
  183. end
  184. # Custom collection
  185. #
  186. class CustomCollection < Base
  187. def products
  188. Product.find(:all, :params => {:collection_id => self.id})
  189. end
  190. def add_product(product)
  191. Collect.create(:collection_id => self.id, :product_id => product.id)
  192. end
  193. def remove_product(product)
  194. collect = Collect.find(:first, :params => {:collection_id => self.id, :product_id => product.id})
  195. collect.destroy if collect
  196. end
  197. end
  198. class SmartCollection < Base
  199. def products
  200. Product.find(:all, :params => {:collection_id => self.id})
  201. end
  202. end
  203. # For adding/removing products from custom collections
  204. class Collect < Base
  205. end
  206. class ShippingAddress < Base
  207. end
  208. class BillingAddress < Base
  209. end
  210. class LineItem < Base
  211. end
  212. class ShippingLine < Base
  213. end
  214. class NoteAttribute < Base
  215. end
  216. class Order < Base
  217. def close; load_attributes_from_response(post(:close)); end
  218. def open; load_attributes_from_response(post(:open)); end
  219. def transactions
  220. Transaction.find(:all, :params => { :order_id => id })
  221. end
  222. def capture(amount = "")
  223. Transaction.create(:amount => amount, :kind => "capture", :order_id => id)
  224. end
  225. end
  226. class Product < Base
  227. # Share all items of this store with the
  228. # shopify marketplace
  229. def self.share; post :share; end
  230. def self.unshare; delete :share; end
  231. # compute the price range
  232. def price_range
  233. prices = variants.collect(&:price)
  234. format = "%0.2f"
  235. if prices.min != prices.max
  236. "#{format % prices.min} - #{format % prices.max}"
  237. else
  238. format % prices.min
  239. end
  240. end
  241. def collections
  242. CustomCollection.find(:all, :params => {:product_id => self.id})
  243. end
  244. def smart_collections
  245. SmartCollection.find(:all, :params => {:product_id => self.id})
  246. end
  247. def add_to_collection(collection)
  248. collection.add_product(self)
  249. end
  250. def remove_from_collection(collection)
  251. collection.remove_product(self)
  252. end
  253. end
  254. class Variant < Base
  255. self.prefix = "/admin/products/:product_id/"
  256. end
  257. class Image < Base
  258. self.prefix = "/admin/products/:product_id/"
  259. # generate a method for each possible image variant
  260. [:pico, :icon, :thumb, :small, :compact, :medium, :large, :original].each do |m|
  261. reg_exp_match = "/\\1_#{m}.\\2"
  262. define_method(m) { src.gsub(/\/(.*)\.(\w{2,4})/, reg_exp_match) }
  263. end
  264. def attach_image(data, filename = nil)
  265. attributes['attachment'] = Base64.encode64(data)
  266. attributes['filename'] = filename unless filename.nil?
  267. end
  268. end
  269. class Transaction < Base
  270. self.prefix = "/admin/orders/:order_id/"
  271. end
  272. class Fulfillment < Base
  273. self.prefix = "/admin/orders/:order_id/"
  274. end
  275. class Country < Base
  276. end
  277. class Page < Base
  278. end
  279. class Blog < Base
  280. def articles
  281. Article.find(:all, :params => { :blog_id => id })
  282. end
  283. end
  284. class Article < Base
  285. self.prefix = "/admin/blogs/:blog_id/"
  286. end
  287. class Metafield < Base
  288. self.prefix = "/admin/:resource/:resource_id/"
  289. # Hack to allow both Shop and other Metafields in through the same AR class
  290. def self.prefix(options={})
  291. options[:resource].nil? ? "/admin/" : "/admin/#{options[:resource]}/#{options[:resource_id]}/"
  292. end
  293. def value
  294. return if attributes["value"].nil?
  295. attributes["value_type"] == "integer" ? attributes["value"].to_i : attributes["value"]
  296. end
  297. end
  298. class Comment < Base
  299. def remove; load_attributes_from_response(post(:remove)); end
  300. def ham; load_attributes_from_response(post(:ham)); end
  301. def spam; load_attributes_from_response(post(:spam)); end
  302. def approve; load_attributes_from_response(post(:approve)); end
  303. end
  304. class Province < Base
  305. self.prefix = "/admin/countries/:country_id/"
  306. end
  307. class Redirect < Base
  308. end
  309. class Webhook < Base
  310. end
  311. class Event < Base
  312. self.prefix = "/admin/:resource/:resource_id/"
  313. # Hack to allow both Shop and other Events in through the same AR class
  314. def self.prefix(options={})
  315. options[:resource].nil? ? "/admin/" : "/admin/#{options[:resource]}/#{options[:resource_id]}/"
  316. end
  317. end
  318. # Assets represent the files that comprise your theme.
  319. # There are different buckets which hold different kinds
  320. # of assets, each corresponding to one of the folders
  321. # within a theme's zip file: layout, templates, and
  322. # assets. The full key of an asset always starts with the
  323. # bucket name, and the path separator is a forward slash,
  324. # like layout/theme.liquid or assets/bg-body.gif.
  325. #
  326. # Initialize with a key:
  327. # asset = ShopifyAPI::Asset.new(:key => 'assets/special.css')
  328. #
  329. # Find by key:
  330. # asset = ShopifyAPI::Asset.find('assets/image.png')
  331. #
  332. # Get the text or binary value:
  333. # asset.value # decodes from attachment attribute if necessary
  334. #
  335. # You can provide new data for assets in a few different ways:
  336. #
  337. # * assign text data for the value directly:
  338. # asset.value = "div.special {color:red;}"
  339. #
  340. # * provide binary data for the value:
  341. # asset.attach(File.read('image.png'))
  342. #
  343. # * set a URL from which Shopify will fetch the value:
  344. # asset.src = "http://mysite.com/image.png"
  345. #
  346. # * set a source key of another of your assets from which
  347. # the value will be copied:
  348. # asset.source_key = "assets/another_image.png"
  349. class Asset < Base
  350. self.primary_key = 'key'
  351. # find an asset by key:
  352. # ShopifyAPI::Asset.find('layout/theme.liquid')
  353. def self.find(*args)
  354. if args[0].is_a?(Symbol)
  355. super
  356. else
  357. params = {:asset => {:key => args[0]}}
  358. params = params.merge(args[1][:params]) if args[1] && args[1][:params]
  359. find(:one, :from => "/admin/assets.#{format.extension}", :params => params)
  360. end
  361. end
  362. # For text assets, Shopify returns the data in the 'value' attribute.
  363. # For binary assets, the data is base-64-encoded and returned in the
  364. # 'attachment' attribute. This accessor returns the data in both cases.
  365. def value
  366. attributes['value'] ||
  367. (attributes['attachment'] ? Base64.decode64(attributes['attachment']) : nil)
  368. end
  369. def attach(data)
  370. self.attachment = Base64.encode64(data)
  371. end
  372. def destroy #:nodoc:
  373. connection.delete(element_path(:asset => {:key => key}), self.class.headers)
  374. end
  375. def new? #:nodoc:
  376. false
  377. end
  378. def self.element_path(id, prefix_options = {}, query_options = nil) #:nodoc:
  379. prefix_options, query_options = split_options(prefix_options) if query_options.nil?
  380. "#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}"
  381. end
  382. def method_missing(method_symbol, *arguments) #:nodoc:
  383. if %w{value= attachment= src= source_key=}.include?(method_symbol)
  384. wipe_value_attributes
  385. end
  386. super
  387. end
  388. private
  389. def wipe_value_attributes
  390. %w{value attachment src source_key}.each do |attr|
  391. attributes.delete(attr)
  392. end
  393. end
  394. end
  395. class RecurringApplicationCharge < Base
  396. undef_method :test
  397. def self.current
  398. find(:all).find{|charge| charge.status == 'active'}
  399. end
  400. def cancel
  401. load_attributes_from_response(self.destroy)
  402. end
  403. def activate
  404. load_attributes_from_response(post(:activate))
  405. end
  406. end
  407. class ApplicationCharge < Base
  408. undef_method :test
  409. def activate
  410. load_attributes_from_response(post(:activate))
  411. end
  412. end
  413. class ProductSearchEngine < Base
  414. end
  415. # Include Metafields module in all enabled classes
  416. METAFIELD_ENABLED_CLASSES.each do |klass|
  417. "ShopifyAPI::#{klass}".constantize.send(:include, Metafields)
  418. end
  419. # Include Events module in all enabled classes
  420. EVENT_ENABLED_CLASSES.each do |klass|
  421. "ShopifyAPI::#{klass}".constantize.send(:include, Events)
  422. end
  423. end