├── README.md ├── SnipcartWebhooksPlugin.php ├── LICENSE └── controllers └── SnipcartWebhooks_WebhooksController.php /README.md: -------------------------------------------------------------------------------- 1 | snipcart-craft-webhooks-plugin 2 | ============================== 3 | 4 | Sample plugin to allow inventory management in a Craft application using Snipcart. 5 | 6 | This repository contains code related to [Managing Your Craft Inventory Using Snipcart Webhooks](https://snipcart.com/blog/managing-your-craft-inventory-using-snipcart-webhooks/) blog post. 7 | -------------------------------------------------------------------------------- /SnipcartWebhooksPlugin.php: -------------------------------------------------------------------------------- 1 | requirePostRequest(); 11 | 12 | $json = craft()->request->getRawBody(); 13 | $body = json_decode($json, true); 14 | 15 | if (is_null($body) or !isset($body['eventName'])) { 16 | $this->returnBadRequest(); 17 | return; 18 | } 19 | 20 | switch ($body['eventName']) { 21 | case 'order.completed': 22 | // We handle the order.completed event. 23 | $this->processOrderCompletedEvent($body); 24 | break; 25 | default: 26 | $this->returnBadRequest(array('reason' => 'Unsupported event')); 27 | break; 28 | } 29 | } 30 | 31 | private function returnBadRequest($errors = array()) { 32 | header('HTTP/1.1 400 Bad Request'); 33 | $this->returnJson(array('success' => false, 'errors' => $errors)); 34 | } 35 | 36 | private function processOrderCompletedEvent($data) { 37 | $content = $data['content']; 38 | $updated = array(); 39 | 40 | foreach ($content['items'] as $item) { 41 | $entry = $this->updateItemQuantity($item); 42 | 43 | if ($entry != null) { 44 | $updated[] = $entry; 45 | } 46 | } 47 | 48 | $this->returnJson($updated); 49 | } 50 | 51 | private function updateItemQuantity($item) { 52 | $service = craft()->entries; 53 | 54 | $entry = $service->getEntryById($item['id']); 55 | 56 | if ($entry != null) { 57 | $attrs = $entry->getContent(); 58 | 59 | $newQuantity = $attrs['quantity'] - $item['quantity']; 60 | 61 | $entry->getContent()->setAttributes(array( 62 | 'quantity' => $newQuantity 63 | )); 64 | 65 | $service->saveEntry($entry); 66 | 67 | return $entry; 68 | } else { 69 | return null; 70 | } 71 | } 72 | } --------------------------------------------------------------------------------