Subversion Repositories munaweb

Rev

Rev 2 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
// be sure include path contains current directory
ini_set('include_path', ini_get('include_path') . ':./php:../ebay/notifications');

// Load general helper classes for Shopify API
require_once 'eBay.php';
require_once 'shopifyConfig.php';
getShopifyConfig();

// Initialize data variable
$data = "";

// Get data and read it into a string
$dataFP = fopen('php://input' , 'rb');
while (!feof($dataFP)) { $data .= fread($dataFP, 4096); }
fclose($dataFP);

$hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];
$verified = verify_webhook($data, $hmac_header);

// Let Shopify know the request is malformed and exit
if (!$verified) {
    errorLog('Webhook verification', var_export($verified, true));
    header('HTTP/1.0 400 Bad request');
    exit();
}

// Let Shopify know the request has been received
ob_start();    // Buffer all upcoming output...
header('HTTP/1.0 200 OK');
header("Connection: close");    // Close the connection.
ob_end_flush();    // Flush all output.
ob_flush();
flush();
if(session_id()) session_write_close();    // Close current session (if it exists).

// Save Webhook action
$action = $_GET['action'];

// Create XML or JSON from data
if ($action == 'transactionCreate') {
  $json = json_decode($data);
  $output = print_r(json_decode($data, JSON_PRETTY_PRINT), true);
  $ext = 'json';
} else {
  $xml = new SimpleXMLElement($data);

  $dom = new DOMDocument('1.0');
  $dom->preserveWhiteSpace = false;
  $dom->formatOutput = true;
  $dom->loadXML($xml->asXML());
  $output = $dom->saveXML();

  $ext = 'xml';
}

// Save formatted XML/JSON in appropriate file
file_put_contents('captures/' . $action . '-' . date('Y-m-d-H.i.s') . '.' . $ext, $output, FILE_APPEND);

// Process XML/JSON
if (substr($action, 0, 5) === 'order') { // ----- Order -----
  // Get Order Name
  if ($action == "orderDelete") {
    $orderName = "Id " . trim($xml->id);
  } else {
    $orderName = trim($xml->name);
  }

  if ($action == "orderPaid") {
    $lockFile = ".lock/$orderName";
    $lockFileFlag = file_exists($lockFile);
        // prevent handling multiple notifications
        if (!$lockFileFlag) { file_put_contents($lockFile, ""); }
  }

  // Get titles, quantities and skus from line items
  $lineItems = array();
  foreach ($xml->{'line-items'}->{'line-item'} as $lineItem) {
    array_push($lineItems, array(trim($lineItem->title), trim($lineItem->quantity), trim($lineItem->sku)));
  }

  $last = count($lineItems) - 1;
  $str = "";
  foreach ($lineItems as $i => $row)
  {
    $isFirst = ($i == 0);
    $isLast = ($i == $last);

        if ($isFirst) {
                $str .= " (";
        } else {
                $str .= "; ";
        }

    $str .= "Title=\"" . $row[0] . "\" Qty=" . $row[1] . " SKU=" . $row[2];

        if ($isLast) {
                $str .= ")";
        }

    if ($action == "orderPaid" && !$lockFileFlag) {
          // Handle eBay Listing
      $list = eBayProductAdjust($row[0], intval($row[1]));
      webhookLog($action, "eBay adjust " . $row[0] . ": " . $list[1]);
          if ($list[0] == false) {
        errorLog($action, "eBay adjust " . $row[0] . ": " . $list[1]);
          }
    }
  }

  webhookLog($action, "Order $orderName" . $str);
} else if (substr($action, 0, 7) === 'product') { // ----- Product -----
  $productId = trim($xml->id);
  // xxxxx Title

  if ($action == "productCreate") {
  } else if ($action == "productUpdate") {
  } else if ($action == "productDelete") {
  }

  webhookLog($action, "Id=$productId");
} else if (substr($action, 0, 8) === 'customer') { // ----- Customer -----
  $customerId = trim($xml->id);
  if ($action == "customerDelete") {
        $customerName= "";
  } else {
    $customerFirstName = trim($xml->{'first-name'});
    $customerLastName = trim($xml->{'last-name'});
        $customerName= ", Name=$customerFirstName $customerLastName";
  }

  webhookLog($action, "Id=$customerId" . $customerName);
} else if (substr($action, 0, 11) === 'fulfillment') { // ----- Fulfillment -----
  $orderName = trim($xml->name);

  if ($action == "fulfillmentCreate") {
  } else if ($action == "fulfillmentUpdate") {
  }

  webhookLog($action, "Order $orderName");
} else if ($action == 'transactionCreate') { // ----- Transaction -----
  $tranId = $json->id;
  $tranOrderId = $json->order_id;
  $tranKind = $json->kind;
  $tranStatus = $json->status;
  $tranAmount = $json->amount;
  //$tranCurrency = $json->currency;

  webhookLog($action, "Id=$tranId, Order Id=$tranOrderId, kind=$tranKind, status=$tranStatus, amount=$tranAmount");
} else if ($action == 'refundCreate') { // ----- Refund -----
  $refundId = trim($xml->id);
  $orderId = trim($xml->{'order-id'});

  webhookLog($action, "Id=$refundId, Order Id=$orderId");
} else if ($action == 'shopUpdate') { // ----- Shop -----
  $shopId = trim($xml->id);
  $shopName = trim($xml->name);

  webhookLog($action, "Id=$shopId, Name=$shopName");
}

function webhookLog($Action, $String) {
  $datestamp = "[" . date("d-M-Y H:i:s") . "] ";
  file_put_contents('webhook.log', $datestamp . $Action . ': ' . $String . "\n", FILE_APPEND);
}

function errorLog($Action, $String) {
  global $fromEmail;
  global $toEmail;

  $subject = "Shopify Webhook Alert";
  $headers = "MIME-Version: 1.0" . "\n";
  $headers .= "Content-type:text/html;charset=UTF-8" . "\n";
  $headers .= "From: Shopify Webhook <$fromEmail>" . "\n";
  $message = "
  <html>
    <head>
      <title>Shopify Webhook Alert</title>
    </head>
    <body>
      <h1>Alert</h1>
      <table>
        <tr>
          <th>Action</th>
          <th>Message</th>
        </tr>
        <tr>
          <td>" . $Action . "</td>
          <td>" . $String . "</td>
        </tr>
      </table>
    </body>
  </html>
  ";

  error_log($Action . ": " . $String);
  mail($toEmail,$subject,$message,$headers,"-f".$fromEmail);
}


exit();
?>