shopify_api.rb 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. require 'ostruct'
  2. require 'digest/md5'
  3. module ShopifyAPI
  4. #
  5. # The Shopify API authenticates each call via HTTP Authentication, using
  6. # * the application's API key as the username, and
  7. # * a hex digest of the application's shared secret and an
  8. # authentication token as the password.
  9. #
  10. # Generation & acquisition of the beforementioned looks like this (assuming the ):
  11. #
  12. # 0. Developer (that's you) registers Application (and provides a
  13. # callback url) and receives an API key and a shared secret
  14. #
  15. # 1. User visits Application and are told they need to authenticate the
  16. # application first for read/write permission to their data (needs to
  17. # happen only once). User is asked for their shop url.
  18. #
  19. # 2. Application redirects to Shopify : GET <user's shop url>/admin/api/auth?app=<API key>
  20. # (See Session#create_permission_url)
  21. #
  22. # 3. User logs-in to Shopify, approves application permission request
  23. #
  24. # 4. Shopify redirects to the Application's callback url (provided during
  25. # registration), including the shop's name, and an authentication token in the parameters:
  26. # GET client.com/customers?shop=snake-oil.myshopify.com&t=a94a110d86d2452eb3e2af4cfb8a3828
  27. #
  28. # 5. Authentication password computed using the shared secret and the
  29. # authentication token (see Session#computed_password)
  30. #
  31. # 6. Profit!
  32. # (API calls can now authenticate through HTTP using the API key, and
  33. # computed password)
  34. #
  35. # LoginController and ShopifyLoginProtection use the Session class to set ActiveResource::Base.site
  36. # so that all API calls are authorized transparently and end up just looking like this:
  37. #
  38. # # get 3 products
  39. # @products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
  40. #
  41. # # get latest 3 orders
  42. # @orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
  43. #
  44. # As an example of what your LoginController should look like, take a look
  45. # at the following:
  46. #
  47. # class LoginController < ApplicationController
  48. # def index
  49. # # Ask user for their #{shop}.myshopify.com address
  50. # end
  51. #
  52. # def authenticate
  53. # redirect_to ShopifyAPI::Session.new(params[:shop]).create_permission_url
  54. # end
  55. #
  56. # # Shopify redirects the logged-in user back to this action along with
  57. # # the authorization token t.
  58. # #
  59. # # This token is later combined with the developer's shared secret to form
  60. # # the password used to call API methods.
  61. # def finalize
  62. # shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
  63. # if shopify_session.valid?
  64. # session[:shopify] = shopify_session
  65. # flash[:notice] = "Logged in to shopify store."
  66. #
  67. # return_address = session[:return_to] || '/home'
  68. # session[:return_to] = nil
  69. # redirect_to return_address
  70. # else
  71. # flash[:error] = "Could not log in to Shopify store."
  72. # redirect_to :action => 'index'
  73. # end
  74. # end
  75. #
  76. # def logout
  77. # session[:shopify] = nil
  78. # flash[:notice] = "Successfully logged out."
  79. #
  80. # redirect_to :action => 'index'
  81. # end
  82. # end
  83. #
  84. class Session
  85. cattr_accessor :api_key
  86. cattr_accessor :secret
  87. cattr_accessor :protocol
  88. self.protocol = 'https'
  89. attr_accessor :url, :token, :name
  90. def self.setup(params)
  91. params.each { |k,value| send("#{k}=", value) }
  92. end
  93. def initialize(url, token = nil)
  94. url.gsub!(/https?:\/\//, '') # remove http:// or https://
  95. url = "#{url}.myshopify.com" unless url.include?('.') # extend url to myshopify.com if no host is given
  96. self.url, self.token = url, token
  97. end
  98. def shop
  99. Shop.current
  100. end
  101. def create_permission_url
  102. "http://#{url}/admin/api/auth?api_key=#{api_key}"
  103. end
  104. # Used by ActiveResource::Base to make all non-authentication API calls
  105. #
  106. # (ActiveResource::Base.site set in ShopifyLoginProtection#shopify_session)
  107. def site
  108. "#{protocol}://#{api_key}:#{computed_password}@#{url}/admin"
  109. end
  110. def valid?
  111. [url, token].all?
  112. end
  113. private
  114. # The secret is computed by taking the shared_secret which we got when
  115. # registring this third party application and concating the request_to it,
  116. # and then calculating a MD5 hexdigest.
  117. def computed_password
  118. Digest::MD5.hexdigest(secret + token.to_s)
  119. end
  120. end
  121. # Shop object. Use Shop.current to receive
  122. # the shop. Since you can only ever reference your own
  123. # shop this model does not have a .find method.
  124. #
  125. class Shop
  126. def self.current
  127. ActiveResource::Base.find(:one, :from => "/admin/shop.xml")
  128. end
  129. end
  130. # Custom collection
  131. #
  132. class CustomCollection < ActiveResource::Base
  133. def products
  134. Product.find(:all, :params => {:collection_id => self.id})
  135. end
  136. def add_product(product)
  137. Collect.create(:collection_id => self.id, :product_id => product.id)
  138. end
  139. def remove_product(product)
  140. collect = Collect.find(:first, :params => {:collection_id => self.id, :product_id => product.id})
  141. collect.destroy if collect
  142. end
  143. end
  144. class SmartCollection < ActiveResource::Base
  145. def products
  146. Product.find(:all, :params => {:collection_id => self.id})
  147. end
  148. end
  149. # For adding/removing products from custom collections
  150. class Collect < ActiveResource::Base
  151. end
  152. class ShippingAddress < ActiveResource::Base
  153. end
  154. class BillingAddress < ActiveResource::Base
  155. end
  156. class LineItem < ActiveResource::Base
  157. end
  158. class ShippingLine < ActiveResource::Base
  159. end
  160. class Order < ActiveResource::Base
  161. def close; load_attributes_from_response(post(:close)); end
  162. def open; load_attributes_from_response(post(:open)); end
  163. def transactions
  164. Transaction.find(:all, :params => { :order_id => id })
  165. end
  166. def capture(amount = "")
  167. Transaction.create(:amount => amount, :kind => "capture", :order_id => id)
  168. end
  169. end
  170. class Product < ActiveResource::Base
  171. # Share all items of this store with the
  172. # shopify marketplace
  173. def self.share; post :share; end
  174. def self.unshare; delete :share; end
  175. # compute the price range
  176. def price_range
  177. prices = variants.collect(&:price)
  178. format = "%0.2f"
  179. if prices.min != prices.max
  180. "#{format % prices.min} - #{format % prices.max}"
  181. else
  182. format % prices.min
  183. end
  184. end
  185. def collections
  186. CustomCollection.find(:all, :params => {:product_id => self.id})
  187. end
  188. def smart_collections
  189. SmartCollection.find(:all, :params => {:product_id => self.id})
  190. end
  191. def add_to_collection(collection)
  192. collection.add_product(self)
  193. end
  194. def remove_from_collection(collection)
  195. collection.remove_product(self)
  196. end
  197. end
  198. class Variant < ActiveResource::Base
  199. self.prefix = "/admin/products/:product_id/"
  200. end
  201. class Image < ActiveResource::Base
  202. self.prefix = "/admin/products/:product_id/"
  203. # generate a method for each possible image variant
  204. [:pico, :icon, :thumb, :small, :medium, :large, :original].each do |m|
  205. reg_exp_match = "/\\1_#{m}.\\2"
  206. define_method(m) { src.gsub(/\/(.*)\.(\w{2,4})/, reg_exp_match) }
  207. end
  208. def attach_image(data, filename = nil)
  209. attributes[:attachment] = Base64.encode64(data)
  210. attributes[:filename] = filename unless filename.nil?
  211. end
  212. end
  213. class Transaction < ActiveResource::Base
  214. self.prefix = "/admin/orders/:order_id/"
  215. end
  216. class Fulfillment < ActiveResource::Base
  217. self.prefix = "/admin/orders/:order_id/"
  218. end
  219. class Country < ActiveResource::Base
  220. end
  221. class Page < ActiveResource::Base
  222. end
  223. class Blog < ActiveResource::Base
  224. def articles
  225. Article.find(:all, :params => { :blog_id => id })
  226. end
  227. end
  228. class Article < ActiveResource::Base
  229. self.prefix = "/admin/blogs/:blog_id/"
  230. end
  231. class Comment < ActiveResource::Base
  232. def remove; load_attributes_from_response(post(:remove)); end
  233. def ham; load_attributes_from_response(post(:ham)); end
  234. def spam; load_attributes_from_response(post(:spam)); end
  235. def approve; load_attributes_from_response(post(:approve)); end
  236. end
  237. class Province < ActiveResource::Base
  238. self.prefix = "/admin/countries/:country_id/"
  239. end
  240. class Redirect < ActiveResource::Base
  241. end
  242. end