shopify_api.rb 16 KB

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