Skip to content

Instantly share code, notes, and snippets.

@bdunlap
Created September 7, 2011 15:26
Show Gist options
  • Save bdunlap/1200870 to your computer and use it in GitHub Desktop.
Save bdunlap/1200870 to your computer and use it in GitHub Desktop.
Given a Shopify order ID, pulls the order JSON from Shopify API and resends the order to an arbitrary webhook URL.
<?php
$settings = array(
'store-domain' => 'YOUR SHOPIFY DOMAIN HERE',
'api-key' => 'YOUR API KEY HERE',
'api-secret' => 'YOUR API SECRET HERE',
'webhook-url' => 'YOUR WEBHOOK URL HERE, INCLUDING "KEY" PARAMETER IF APPLICABLE',
);
ini_set('display_errors', 'On');
error_reporting(-1);
if (count($argv) !== 2) {
usage();
exit;
}
$orderId = filter_var($argv[1], FILTER_VALIDATE_INT);
if (!$orderId) {
usage();
exit;
}
$orderUrl = "https://{$settings['api-key']}:{$settings['api-secret']}@{$settings['store-domain']}/admin/orders/$orderId.json";
$orderJson = file_get_contents($orderUrl);
if ($orderJson === FALSE) {
echo "Failed to retrieve JSON of order $orderId.\n";
} else {
echo "JSON follows:\n$orderJson\n\n";
$response = json_decode($orderJson);
$innerJson = json_encode($response->order);
$response = post($innerJson, $settings['webhook-url']);
echo "HTTP response body follows.\n$response";
}
function usage()
{
global $argv;
echo "Usage: {$argv[0]} <Shopify order ID>\n";
}
/**
* Lifted from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/
*/
function post($body, $url)
{
global $settings;
$options = array('http' => array(
'method' => 'POST',
'content' => $body,
'header' => "X-Shopify-Shop-Domain: {$settings['store-domain']}",
)
);
$ctx = stream_context_create($options);
$fp = fopen($url, 'rb', FALSE, $ctx);
if (!$fp) {
throw new Exception("Could not open $url with fopen()");
}
$response = stream_get_contents($fp);
if ($response === FALSE) {
throw new Exception("Could not read data from $url: $php_errormsg");
}
return $response;
}
?>
@bdunlap
Copy link
Author

bdunlap commented Sep 8, 2011

This thing needs to generate a signature and send it in a header named 'X-Shopify-HMAC-SHA256': http://wiki.shopify.com/Verifying_Webhooks

@ets
Copy link

ets commented Oct 29, 2013

Still working great after 2 years. Appreciate your post of this time saver!

@magendrats
Copy link

Where to provide Shopify order ID??
didn't get any variable to provide it.
let me know?

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