Subversion Repositories munaweb

Rev

Rev 75 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
<?php
2
// be sure include path contains current directory
75 - 3
ini_set('include_path', ini_get('include_path') . ':./php:../ebay/notifications');
2 - 4
 
5
// Load general helper classes for Shopify API
6
require_once 'eBay.php';
7
require_once 'shopifyConfig.php';
8
getShopifyConfig();
9
 
10
// Initialize data variable
11
$data = "";
12
 
13
// Get data and read it into a string
14
$dataFP = fopen('php://input' , 'rb');
15
while (!feof($dataFP)) { $data .= fread($dataFP, 4096); }
16
fclose($dataFP);
17
 
18
$hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];
19
$verified = verify_webhook($data, $hmac_header);
20
 
21
// Let Shopify know the request is malformed and exit
22
if (!$verified) {
23
    errorLog('Webhook verification', var_export($verified, true));
24
    header('HTTP/1.0 400 Bad request');
25
    exit();
26
}
27
 
28
// Let Shopify know the request has been received
29
ob_start();    // Buffer all upcoming output...
30
header('HTTP/1.0 200 OK');
31
header("Connection: close");    // Close the connection.
32
ob_end_flush();    // Flush all output.
33
ob_flush();
34
flush();
35
if(session_id()) session_write_close();    // Close current session (if it exists).
36
 
37
// Save Webhook action
38
$action = $_GET['action'];
39
 
40
// Create XML or JSON from data
41
if ($action == 'transactionCreate') {
42
  $json = json_decode($data);
43
  $output = print_r(json_decode($data, JSON_PRETTY_PRINT), true);
44
  $ext = 'json';
45
} else {
46
  $xml = new SimpleXMLElement($data);
47
 
48
  $dom = new DOMDocument('1.0');
49
  $dom->preserveWhiteSpace = false;
50
  $dom->formatOutput = true;
51
  $dom->loadXML($xml->asXML());
52
  $output = $dom->saveXML();
53
 
54
  $ext = 'xml';
55
}
56
 
57
// Save formatted XML/JSON in appropriate file
58
file_put_contents('captures/' . $action . '-' . date('Y-m-d-H.i.s') . '.' . $ext, $output, FILE_APPEND);
59
 
60
// Process XML/JSON
61
if (substr($action, 0, 5) === 'order') { // ----- Order -----
62
  // Get Order Name
63
  if ($action == "orderDelete") {
64
    $orderName = "Id " . trim($xml->id);
65
  } else {
66
    $orderName = trim($xml->name);
67
  }
68
 
69
  if ($action == "orderPaid") {
70
    $lockFile = ".lock/$orderName";
71
    $lockFileFlag = file_exists($lockFile);
102 - 72
    // prevent handling multiple notifications
73
    if (!$lockFileFlag) { file_put_contents($lockFile, ""); }
2 - 74
  }
75
 
76
  // Get titles, quantities and skus from line items
77
  $lineItems = array();
78
  foreach ($xml->{'line-items'}->{'line-item'} as $lineItem) {
79
    array_push($lineItems, array(trim($lineItem->title), trim($lineItem->quantity), trim($lineItem->sku)));
80
  }
81
 
82
  $last = count($lineItems) - 1;
83
  $str = "";
84
  foreach ($lineItems as $i => $row)
85
  {
86
    $isFirst = ($i == 0);
87
    $isLast = ($i == $last);
88
 
89
	if ($isFirst) {
90
		$str .= " (";
91
	} else {
92
		$str .= "; ";
93
	}
94
 
95
    $str .= "Title=\"" . $row[0] . "\" Qty=" . $row[1] . " SKU=" . $row[2];
96
 
97
	if ($isLast) {
98
		$str .= ")";
99
	}
100
 
101
    if ($action == "orderPaid" && !$lockFileFlag) {
102
   	  // Handle eBay Listing
103
      $list = eBayProductAdjust($row[0], intval($row[1]));
104
      webhookLog($action, "eBay adjust " . $row[0] . ": " . $list[1]);
105
	  if ($list[0] == false) {
106
        errorLog($action, "eBay adjust " . $row[0] . ": " . $list[1]);
107
	  }
108
    }
109
  }
110
 
111
  webhookLog($action, "Order $orderName" . $str);
112
} else if (substr($action, 0, 7) === 'product') { // ----- Product -----
113
  $productId = trim($xml->id);
114
  // xxxxx Title
115
 
116
  if ($action == "productCreate") {
117
  } else if ($action == "productUpdate") {
118
  } else if ($action == "productDelete") {
119
  }
120
 
121
  webhookLog($action, "Id=$productId");
122
} else if (substr($action, 0, 8) === 'customer') { // ----- Customer -----
123
  $customerId = trim($xml->id);
124
  if ($action == "customerDelete") {
125
  	$customerName= "";
126
  } else {
127
    $customerFirstName = trim($xml->{'first-name'});
128
    $customerLastName = trim($xml->{'last-name'});
129
  	$customerName= ", Name=$customerFirstName $customerLastName";
130
  }
131
 
132
  webhookLog($action, "Id=$customerId" . $customerName);
133
} else if (substr($action, 0, 11) === 'fulfillment') { // ----- Fulfillment -----
134
  $orderName = trim($xml->name);
135
 
136
  if ($action == "fulfillmentCreate") {
137
  } else if ($action == "fulfillmentUpdate") {
138
  }
139
 
140
  webhookLog($action, "Order $orderName");
141
} else if ($action == 'transactionCreate') { // ----- Transaction -----
142
  $tranId = $json->id;
143
  $tranOrderId = $json->order_id;
144
  $tranKind = $json->kind;
145
  $tranStatus = $json->status;
146
  $tranAmount = $json->amount;
147
  //$tranCurrency = $json->currency;
148
 
149
  webhookLog($action, "Id=$tranId, Order Id=$tranOrderId, kind=$tranKind, status=$tranStatus, amount=$tranAmount");
150
} else if ($action == 'refundCreate') { // ----- Refund -----
151
  $refundId = trim($xml->id);
152
  $orderId = trim($xml->{'order-id'});
153
 
154
  webhookLog($action, "Id=$refundId, Order Id=$orderId");
155
} else if ($action == 'shopUpdate') { // ----- Shop -----
156
  $shopId = trim($xml->id);
157
  $shopName = trim($xml->name);
158
 
159
  webhookLog($action, "Id=$shopId, Name=$shopName");
160
}
161
 
162
function webhookLog($Action, $String) {
163
  $datestamp = "[" . date("d-M-Y H:i:s") . "] ";
164
  file_put_contents('webhook.log', $datestamp . $Action . ': ' . $String . "\n", FILE_APPEND);
165
}
166
 
167
function errorLog($Action, $String) {
168
  global $fromEmail;
169
  global $toEmail;
170
 
171
  $subject = "Shopify Webhook Alert";
172
  $headers = "MIME-Version: 1.0" . "\n";
173
  $headers .= "Content-type:text/html;charset=UTF-8" . "\n";
174
  $headers .= "From: Shopify Webhook <$fromEmail>" . "\n";
175
  $message = "
176
  <html>
177
    <head>
178
      <title>Shopify Webhook Alert</title>
179
    </head>
180
    <body>
181
      <h1>Alert</h1>
182
      <table>
183
        <tr>
184
          <th>Action</th>
185
          <th>Message</th>
186
        </tr>
187
        <tr>
188
          <td>" . $Action . "</td>
189
          <td>" . $String . "</td>
190
        </tr>
191
      </table>
192
    </body>
193
  </html>
194
  ";
195
 
196
  error_log($Action . ": " . $String);
197
  mail($toEmail,$subject,$message,$headers,"-f".$fromEmail);
198
}
199
 
200
 
201
exit();
75 - 202
?>