custom/plugins/armbrMailbeez/src/Resources/MBApiClient/classes/MBWebhook.php line 219

Open in your IDE?
  1. <?php
  2. /**
  3.  *
  4.  *
  5.  * @api      {HIDE} \MBWebhook::__construct() How to implement
  6.  * @apiVersion 1.0.0
  7.  * @apiName    Implement
  8.  * @apiGroup   Webhooks
  9.  *
  10.  * @apiDescription
  11.  * The Webhook is an URL on the client system, which can be called by the MailBeez.io Server to trigger actions.
  12.  *
  13.  * The provided MBWebhook class covers the common functionality and will help you to focus on building listener Methods.
  14.  *
  15.  * The Webhook task name is automatically mapped to a matching listener method - if the method does not exists, an error is given.
  16.  *
  17.  * So e.g. for a Webhook Call `myTask` you would need to implement the method `listenerMyTask()` with a meaningful functionality.
  18.  *
  19.  * Everytime MailBeez.io calls the Webhook "myTask" the matching method will be called and must return an array (can be empty).
  20.  *
  21.  * Some predefined System tasks require a specified return array.
  22.  *
  23.  *
  24.  * @apiParamExample {php} Code Example
  25.  *
  26.  * // content of webhook.php
  27.  *
  28.  * include('classes/MBWebhook.php');
  29.  *
  30.  * class MyWebhook extends MBWebhook
  31.  * {
  32.  *
  33.  *    // set api credentials for $this->apiClient
  34.  *    var $apihost = 'theHostUrl';
  35.  *    var $apiuser = 'theApiUser';
  36.  *    var $apipass = 'theApiPass';
  37.  *
  38.  *    public function listenerMyTask($request)
  39.  *    {
  40.  *        // implement logic to perform the Task
  41.  *        // use apiCall
  42.  *        // $response = $this->apiClient->updateCustomers($request->cId, $customerData);
  43.  *
  44.  *        // dummy response with some output
  45.  *        $starttime = microtime(true);
  46.  *
  47.  *        sleep(rand(1,2));
  48.  *
  49.  *        // the php array will be automatically converted into JSON
  50.  *        $response = array(
  51.  *            'code' => 200, // specify if you want to change
  52.  *            'status' => 'success', // specify if you want to change
  53.  *            'cId' => $request->cId,
  54.  *            'ptime' => round((microtime(true) - $starttime) * 1000)
  55.  *        );
  56.  *
  57.  *        return $response;
  58.  *    }
  59.  *
  60.  * }
  61.  * new MyWebhook(); // automatically outputs JSON header and result, exit();
  62.  *
  63.  * // alternative - get result
  64.  * // $result = new MyWebhook(false); // disable JSON output
  65.  * // print_r($result->getResult()); // get result array
  66.  *
  67.  *
  68.  *
  69.  * @apiParamExample {json} Request Example
  70.  * // will be automatically encoded into a $request Object
  71.  * {
  72.  *     "task": "myTask",
  73.  *     "payload": {
  74.  *         "cId": "c425",
  75.  *         "fields": [
  76.  *             "email"
  77.  *         ]
  78.  *     }
  79.  * }
  80.  *
  81.  *
  82.  * @apiSuccess (Default Response Array) {Number} [code=200] Http response-Code
  83.  * @apiSuccess (Default Response Array) {String{success, error}} [status=success] Status
  84.  * @apiSuccess (Default Response Array) {Custom} [CustomResponse] The response array will be logged, so you can provide anything helpful
  85.  *
  86.  * @apiSuccessExample {json} Response Example
  87.  * {
  88.  *    "code": 200,
  89.  *    "status": "success",
  90.  *    "cId": "c42",
  91.  *    "ptime": 1075
  92.  * }
  93.  *
  94.  * @apiErrorExample {json} Unknown Task 400:
  95.  * {
  96.  *    "code": 400,
  97.  *    "status": "error",
  98.  *    "message": "Could not find method listenerUnknownTask - unknown Task: unknownTask"
  99.  * }
  100.  */
  101. /**
  102.  *
  103.  *
  104.  * @api      {HIDE} \MBWebhook::__construct() Test your Code
  105.  * @apiVersion 1.0.0
  106.  * @apiName    Test
  107.  * @apiGroup   Webhooks
  108.  *
  109.  * @apiDescription
  110.  * For easy testing we recommend to use [Postman](https://www.getpostman.com/). Just configure a new POST request targeting your
  111.  * Webhook URL with some meaningfull Body of type "raw" with content-type "JSON (application/json)"
  112.  *
  113.  * ![image](test_webhook.png)
  114.  *
  115.  * Postman will show you the output of the webhook request.
  116.  *
  117.  */
  118. include('MBApiClient.php');
  119. include('MBWebhookInterface.php');
  120. Class MBWebhook
  121. {
  122.     protected $apihost;
  123.     protected $apiuser;
  124.     protected $apipass;
  125.     /**
  126.      * @return mixed
  127.      */
  128.     public function getApihost()
  129.     {
  130.         return $this->apihost;
  131.     }
  132.     /**
  133.      * @param mixed $apihost
  134.      */
  135.     public function setApihost($apihost)
  136.     {
  137.         $this->apihost $apihost;
  138.     }
  139.     /**
  140.      * @return mixed
  141.      */
  142.     public function getApiuser()
  143.     {
  144.         return $this->apiuser;
  145.     }
  146.     /**
  147.      * @param mixed $apiuser
  148.      */
  149.     public function setApiuser($apiuser)
  150.     {
  151.         $this->apiuser $apiuser;
  152.     }
  153.     /**
  154.      * @return mixed
  155.      */
  156.     public function getApipass()
  157.     {
  158.         return $this->apipass;
  159.     }
  160.     /**
  161.      * @param mixed $apipass
  162.      */
  163.     public function setApipass($apipass)
  164.     {
  165.         $this->apipass $apipass;
  166.     }
  167.     var $result;
  168.     /** @var \MBApiClient */
  169.     var $apiClient;
  170.     var $defaultErrorResponse;
  171.     var $defaultSuccessResponse;
  172.     public function __construct($inputObj false$outputJson true$autorun false)
  173.     {
  174.         $this->defaultErrorResponse = array(
  175.             'code' => 400,
  176.             'status' => 'error'
  177.         );
  178.         $this->defaultSuccessResponse = array(
  179.             'code' => 200,
  180.             'status' => 'success'
  181.         );
  182.         $this->outputJson $outputJson;
  183.         if ($autorun) {
  184.             $this->__init();
  185.             $this->process($inputObj);
  186.         }
  187.     }
  188.     public function __init() {
  189.         $this->apiClient = new MBApiClient($this->getApihost(), $this->getApiuser(), $this->getApipass());
  190.     }
  191.     public function process($inputObj null$context)
  192.     {
  193.         $response false;
  194.         $methodeName false;
  195.         $obj null;
  196.         $defaultSuccessResponse $this->defaultSuccessResponse;
  197.         $defaultErrorResponse $this->defaultErrorResponse;
  198.         try {
  199.             $obj $this->prepare($inputObj);
  200.             $methodeName 'listener' ucfirst($obj->task);
  201.             if (is_object($obj) && method_exists($this$methodeName)) {
  202.                 try {
  203.                     $responseOfMethod $this->$methodeName($obj->payload$context);
  204.                     $response $responseOfMethod;
  205. //                    $response = $responseOfMethod + $defaultSuccessResponse; //temp disabled
  206.                 } catch (Exception $e) {
  207.                     $defaultErrorResponse['code'] = 500;
  208.                     $msg $e->getMessage();
  209.                     // debug info from curl
  210.                     // \MBApiResponse::__construct
  211.                     if (is_array($msgArray json_decode($msgtrue))) {
  212.                         $defaultErrorResponse $msgArray;
  213.                     } else {
  214.                         $defaultErrorResponse['message'] = 'MB Webhook says (methodeName: ' .$methodeName.'): ' $e->getMessage() . ' - payload: 'print_r($obj->payloadtrue) . '- trace: ' $e->getTraceAsString() . ' - code: ' $e->getCode();
  215.                     }
  216.                 }
  217.             } else {
  218.                 $defaultErrorResponse['message'] = 'Could not find method ' $methodeName ' - unknown Task: ' $obj->task "\n" print_r($inputObjtrue);
  219.             }
  220.         } catch (Exception $e) {
  221.             $defaultErrorResponse['message'] = 'MB Webhook says (task: ' .$obj->task.'): ' $e->getMessage() . ' - payload: 'print_r($obj->payloadtrue);
  222.         }
  223.         $this->result $response;
  224.         return $this;
  225.     }
  226.     public function prepare($inputObj false)
  227.     {
  228.         if (is_object($inputObj)) {
  229.             $obj $inputObj;
  230.         }
  231.         else {
  232.             $json file_get_contents('php://input');
  233.             $obj json_decode($json);
  234.         }
  235.         if (!is_object($obj)) {
  236.             throw new Exception('MBWebhook: malformed JSON: ' file_get_contents('php://input'));
  237.         }
  238.         if (!is_string($obj->task) || !is_object($obj->payload)) {
  239.             throw new Exception('incomplete JSON - missing task or payload');
  240.         }
  241.         return $obj;
  242.     }
  243.     public function _result($response)
  244.     {
  245.         if ($this->outputJson) {
  246.             header('Content-Type: application/json; charset=utf-8');
  247.             $code = ($response['code']) ? $response['code'] : '200';
  248.             http_response_code($code);
  249.             echo json_encode($response);
  250.             exit();
  251.         }
  252.         return $response;
  253.     }
  254.     public function getResult()
  255.     {
  256.         return $this->result;
  257.     }
  258.     function _bulkResponseHandler($response)
  259.     {
  260.         // handle bulk action response
  261.         // summarize into a single response which will be protocolled in the task queue
  262.         if (sizeof($response->result->new) > 0) {
  263.             // successfully created
  264.             $result = array(); // default success result
  265.         } elseif (sizeof($response->result->success) > 0) {
  266.             // successfully updated
  267.             $result = array(); // default success result
  268.         } elseif (sizeof($response->result->invalid) > 0) {
  269.             // invalid data provided
  270.             $result = array(
  271.                 'code' => 400// override
  272.                 'status' => 'error'// override
  273.                 'message' => print_r(json_encode($response->result), true)
  274.             );
  275.         } elseif (sizeof($response->result->exists) > 0) {
  276.             // some items did already exists
  277.             $result = array(
  278.                 'code' => 202// override
  279.                 'status' => 'warning'// override
  280.                 'message' => print_r(json_encode($response->result), true)
  281.             );
  282.         } else {
  283.             // unknown situation
  284.             $result = array(
  285.                 'code' => 400// override
  286.                 'status' => 'error'// override
  287.                 'message' => print_r(json_encode($response->result), true)
  288.             );
  289.         }
  290.         return $result;
  291.     }
  292. }