php - cakephp 和 Webhooks

标签 php json cakephp snipcart

我是 cakephp 新手,并且已经实现了网上商店解决方案 Snipcart。当 snipcart 处理订单时,他们会向我们的网站发送一个 Webhook。根据他们的文档,网络钩子(Hook)看起来像这样:

    {
    eventName: "order:completed",
      mode: "Live",
      createdOn: "2013-07-04T04:18:44.5538768Z",
      content: {
          token: "22808196-0eff-4a6e-b136-3e4d628b3cf5",
          creationDate: "2013-07-03T19:08:28.993Z",
          modificationDate: "2013-07-04T04:18:42.73Z",
          status: "Processed",
          paymentMethod: "CreditCard",
          email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b0a6a0a7bcbeb6a193a0bdbaa3b0b2a1a7fdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>",
          cardHolderName: "Nicolas Cage",
          billingAddressName: "Nicolas Cage",
          billingAddressCompanyName: "Company name",
          billingAddressAddress1: "888 The street",
          billingAddressAddress2: "",
          billingAddressCity: "Québec",
          billingAddressCountry: "CA",
          billingAddressProvince: "QC",
          billingAddressPostalCode: "G1G 1G1",
          billingAddressPhone: "(888) 888-8888",
          shippingAddressName: "Nicolas Cage",
          shippingAddressCompanyName: "Company name",
          shippingAddressAddress1: "888 The street",
          shippingAddressAddress2: "",
          shippingAddressCity: "Québec",
          shippingAddressCountry: "CA",
          shippingAddressProvince: "QC",
          shippingAddressPostalCode: "G1G 1G1",
          shippingAddressPhone: "(888) 888-8888",
          shippingAddressSameAsBilling: true,
          finalGrandTotal: 310.00,
          shippingAddressComplete: true,
          creditCardLast4Digits: "4242",
          shippingFees: 10.00,
          shippingMethod: "Livraison",
          items: [{
              uniqueId: "eb4c9dae-e725-4dad-b7ae-a5e48097c831",
              token: "22808196-0eff-4a6e-b136-3e4d628b3cf5",
              id: "1",
              name: "Movie",
              price: 300.00,
              originalPrice: 300.00,
              quantity: 1,
              url: "https://snipcart.com",
              weight: 10.00,
              description: "Something",
              image: "http://placecage.com/50/50",
              customFieldsJson: "[]",
              stackable: true,
              maxQuantity: null,
              totalPrice: 300.0000,
              totalWeight: 10.00
          }],
          subtotal: 610.0000,
          totalWeight: 20.00,
          hasPromocode: false,
          promocodes: [],
          willBePaidLater: false
      }
}

使用 webhooks 的方式如下所示:

    <?php

$json = file_get_contents('php://input');
$body = json_decode($json, true);

if (is_null($body) or !isset($body['eventName'])) {
    // When something goes wrong, return an invalid status code
    // such as 400 BadRequest.
    header('HTTP/1.1 400 Bad Request');
    return;
}

switch ($body['eventName']) {
    case 'order:completed':
        // This is an order:completed event
        // do what needs to be done here.
        break;
}

// Return a valid status code such as 200 OK.
header('HTTP/1.1 200 OK');

我的问题是,如何在 CakePHP 2.4 版中执行此操作。我已经在互联网上寻找解决方案好几天了,但尽管我缺乏经验,但我找不到合适的解决方案。

解决了:

  public function webhooks(){

  //check if POST
  if ($this->request->is('post')) {
  //Allow raw POST's
  $url = 'php://input';
  //decode
  $json = json_decode(file_get_contents($url), true);

  if (is_null($json) or !isset($json['eventName'])) {
    // When something goes wrong, return an invalid status code
    // such as 400 BadRequest.
    header('HTTP/1.1 400 Bad Request');
    return;
}
  //do whatever needs to be done, in this case remove the quantity ordered from the stock in db.
    switch ($json['eventName']) {
    case 'order:completed':

        $id = $json['content']['items'][0]['id']; 
        $quantity = $json['content']['items'][0]['quantity']; 

        $query = $this->Shop->findById($id, 'Shop.stock');

        $stock = $query['Shop']['stock'];

        $stock = $stock - $quantity;

    $this->Shop->updateAll(array('Shop.stock' => $stock), array('Shop.id' => $id));

    break;

        }

        header('HTTP/1.1 200 OK');

    }
}

最佳答案

我唯一要添加到您的答案中的是做一些事情的更多“蛋糕”方法。

public function webhooks(){

//check if POST
if ($this->request->is('post') || $this->request->is('put')) {
 //Allow raw POST's
$url = 'php://input';
//decode
$json = json_decode(file_get_contents($url), true);

if (empty($json) or empty($json['eventName'])) {
  throw new BadRequestException('Invalid JSON Information');
}
//do whatever needs to be done, in this case remove the quantity ordered from the stock in db.
switch ($json['eventName']) {
case 'order:completed':

    $id = $json['content']['items'][0]['id']; 
    $quantity = $json['content']['items'][0]['quantity']; 

    $shop = $this->Shop->find('first', array(
        'conditions' => array(
               'Shop.id' => $id,
         ),
         'fields' => array(
               'Shop.stock',
         ),
    ));
    if (empty($shop)) {
         throw new NotFoundException(__('Invalid Shop Content'));
    }
    $stock = $shop['Shop']['stock'];

    $stock = $stock - $quantity;
 $this->Shop->id = $id;
 $this->Shop->saveField('stock', $stock);
break;

    }

关于php - cakephp 和 Webhooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19366294/

相关文章:

php - 具有多个搜索过滤器的 Cake PHP3 分页

php - 在数据库 MYSQL 中插入数据,数据混合

php - 将 bool 值转换为整数

python - 替换 JSON 文件中的字符串

Java - 向下转型时出现 ClassCastException

php - Cakephp根据请求保存数据

php - Cakephp 3 - 从数据库中减去一个值

javascript - 使用 JavaScript/PHP 将文本复制到剪贴板

json - React Native 打包器找不到 package.json

validation - CakePHP "Agree TOS"复选框验证