shopify_api.rb 13 KB

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