Skip to content

Instantly share code, notes, and snippets.

@elzii
Created June 21, 2015 23:45
Show Gist options
  • Save elzii/4c7061c843e02ac5bbdb to your computer and use it in GitHub Desktop.
Save elzii/4c7061c843e02ac5bbdb to your computer and use it in GitHub Desktop.
Shopify Meteor Simple API (Private Apps)
/**
* Shopify Client API
*/
Shopify = {}
var API = Shopify.API = function ShopifyAPI(options) {
this.config = {
shop: options.shop,
api_key: options.api_key || null,
password: options.password || null,
debug: options.debug || false
}
this.getCredentials = function() {
return this.config;
}
this.getPrivateAppHeaders = function() {
return this.config.api_key + ":" + this.config.password;
}
this.getBaseAPIURL = function() {
var url = 'https://'+this.config.shop+'.myshopify.com/';
return url;
}
this.getBaseAPIURLWithCredentials = function() {
var url = 'https://'+this.config.api_key+':'+this.config.password+'@'+this.config.shop+'.myshopify.com/';
return url;
}
/**
* Shopify Request
*
* @param {String} method
* @param {String} endpoint
* @param {Object} options
* {
* content : '' // string to use as the http request body
* data : { }, // JSON-able object to use as http request body. overwrites content
* params : '', // URL params
* auth : '', // basic auth in the form of username:password
* headers : '', // dict of strings
* timeout : null, // timeout
* }
*
* @param {Function} callback
*/
this.request = function(method, endpoint, options, callback) {
var method = method || 'GET',
endpoint = endpoint || '',
options = options || {};
options.auth = this.getPrivateAppHeaders()
// Checks
// check(method, String)
// check(endpoint, String)
// check(options, Object)
// check(callback, Function)
var api_url = this.getBaseAPIURL()
try {
var result = HTTP.call(method, (api_url + endpoint), options )
if (200 <= result.statusCode && result.statusCode <= 299) {
return result.data;
}
} catch (e) {
// network error
return false;
}
}
}
/**
* Meteor Shopify Methods
*/
Meteor.methods(
{
exampleShopifyGETRequest: function() {
return ShopifyAPI.request('GET', 'admin/custom_collections.json', {})
},
exampleShopifyPOSTRequest: function(collection_id, image_src) {
return ShopifyAPI.request('POST', 'admin/custom_collections/'+collection_id+'.json', {
data : {
custom_collection : {
id : collection_id,
image : {
src : image_src
}
}
}
})
}
})
/**
* Init Shopify API
*/
ShopifyAPI = new Shopify.API({
debug: true,
shop: "<STORE_NAME>",
api_key: "<API_KEY>",
password: "<PASSWORD>"
})
/**
* Client Usage
*/
Meteor.call('exampleShopifyGETRequest', function (err, res) {
console.log( 'data', err, res )
})
Meteor.call('exampleShopifyPOSTRequest', 'http://i.imgur.com/BTNIDBR.gif', function (err, res) {
console.log( 'data', err, res )
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment