Skip to content

Instantly share code, notes, and snippets.

@jimmynguyc
Created May 23, 2020 03:49
Show Gist options
  • Save jimmynguyc/55a395419d1e1d249ebf9a39cf5c3d38 to your computer and use it in GitHub Desktop.
Save jimmynguyc/55a395419d1e1d249ebf9a39cf5c3d38 to your computer and use it in GitHub Desktop.
Overcoming lack of publication_write permission for Shopify private apps
require "byebug"
require "time"
require "capybara/cuprite"
require "capybara/dsl"
require "capybara/rspec/matchers"
require "rspec/expectations"
include Capybara::DSL
include Capybara::RSpecMatchers
Capybara.register_driver(:cuprite) do |app|
chrome_path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
Capybara::Cuprite::Driver.new(app, window_size: [1200, 800], headless: false, timeout: 60, browser_path: chrome_path)
end
Capybara.default_driver = :cuprite
product_id = "4911526084667"
publication_id = "50348556347"
publication_time = Time.now.utc.iso8601
shop_name = ENV['SHOP_NAME']
action = "publish" # [publish|unpublish]
visit "https://#{shop_name}.myshopify.com/admin/products/#{product_id}"
fill_in "account[email]", with: ENV['SHOPIFY_USERNAME']
page.find("button[name=commit]").click
fill_in "account[password]", with: ENV['SHOPIFY_PASSWORD']
page.find("button[name=commit]").click
page.should have_content("Product availability")
payload = if action == "publish"
%Q|{"operationName":"AddPublications","variables":{"id":"gid://shopify/Product/#{product_id}","input":[{"publicationId":"gid://shopify/Publication/#{publication_id}","publishDate":"#{publication_time}"}]},"query":"mutation AddPublications($id: ID!, $input: [PublicationInput!]!) {\\n publishablePublish(id: $id, input: $input) {\\n userErrors {\\n field\\n message\\n __typename\\n }\\n __typename\\n }\\n}\\n"}|
else
%Q|{"operationName":"DeletePublications","variables":{"id":"gid://shopify/Product/#{product_id}","input":[{"publicationId":"gid://shopify/Publication/#{publication_id}"}]},"query":"mutation DeletePublications($id: ID!, $input: [PublicationInput!]!) {\\n publishableUnpublish(id: $id, input: $input) {\\n userErrors {\\n field\\n message\\n __typename\\n }\\n __typename\\n }\\n}\\n"}|
js = <<-SCRIPT
var csrf;
for (i=0; i<document.scripts.length; i++) {
s = document.scripts[i];
if(s.dataset.serializedId == "csrf") {
csrf = JSON.parse(s.innerHTML);
break;
}
}
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://#{shop_name}.myshopify.com/admin/internal/web/graphql/core");
xhttp.setRequestHeader("x-csrf-token", csrf);
xhttp.setRequestHeader("Accept", "application/json");
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(`#{payload}`)
SCRIPT
page.browser.execute_script(js)
@janoschp
Copy link

this is genius 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment