<?php
/**
*
*
* @api {HIDE} \MBWebhook::__construct() How to implement
* @apiVersion 1.0.0
* @apiName Implement
* @apiGroup Webhooks
*
* @apiDescription
* The Webhook is an URL on the client system, which can be called by the MailBeez.io Server to trigger actions.
*
* The provided MBWebhook class covers the common functionality and will help you to focus on building listener Methods.
*
* The Webhook task name is automatically mapped to a matching listener method - if the method does not exists, an error is given.
*
* So e.g. for a Webhook Call `myTask` you would need to implement the method `listenerMyTask()` with a meaningful functionality.
*
* Everytime MailBeez.io calls the Webhook "myTask" the matching method will be called and must return an array (can be empty).
*
* Some predefined System tasks require a specified return array.
*
*
* @apiParamExample {php} Code Example
*
* // content of webhook.php
*
* include('classes/MBWebhook.php');
*
* class MyWebhook extends MBWebhook
* {
*
* // set api credentials for $this->apiClient
* var $apihost = 'theHostUrl';
* var $apiuser = 'theApiUser';
* var $apipass = 'theApiPass';
*
* public function listenerMyTask($request)
* {
* // implement logic to perform the Task
* // use apiCall
* // $response = $this->apiClient->updateCustomers($request->cId, $customerData);
*
* // dummy response with some output
* $starttime = microtime(true);
*
* sleep(rand(1,2));
*
* // the php array will be automatically converted into JSON
* $response = array(
* 'code' => 200, // specify if you want to change
* 'status' => 'success', // specify if you want to change
* 'cId' => $request->cId,
* 'ptime' => round((microtime(true) - $starttime) * 1000)
* );
*
* return $response;
* }
*
* }
* new MyWebhook(); // automatically outputs JSON header and result, exit();
*
* // alternative - get result
* // $result = new MyWebhook(false); // disable JSON output
* // print_r($result->getResult()); // get result array
*
*
*
* @apiParamExample {json} Request Example
* // will be automatically encoded into a $request Object
* {
* "task": "myTask",
* "payload": {
* "cId": "c425",
* "fields": [
* "email"
* ]
* }
* }
*
*
* @apiSuccess (Default Response Array) {Number} [code=200] Http response-Code
* @apiSuccess (Default Response Array) {String{success, error}} [status=success] Status
* @apiSuccess (Default Response Array) {Custom} [CustomResponse] The response array will be logged, so you can provide anything helpful
*
* @apiSuccessExample {json} Response Example
* {
* "code": 200,
* "status": "success",
* "cId": "c42",
* "ptime": 1075
* }
*
* @apiErrorExample {json} Unknown Task 400:
* {
* "code": 400,
* "status": "error",
* "message": "Could not find method listenerUnknownTask - unknown Task: unknownTask"
* }
*/
/**
*
*
* @api {HIDE} \MBWebhook::__construct() Test your Code
* @apiVersion 1.0.0
* @apiName Test
* @apiGroup Webhooks
*
* @apiDescription
* For easy testing we recommend to use [Postman](https://www.getpostman.com/). Just configure a new POST request targeting your
* Webhook URL with some meaningfull Body of type "raw" with content-type "JSON (application/json)"
*
* 
*
* Postman will show you the output of the webhook request.
*
*/
include('MBApiClient.php');
include('MBWebhookInterface.php');
Class MBWebhook
{
protected $apihost;
protected $apiuser;
protected $apipass;
/**
* @return mixed
*/
public function getApihost()
{
return $this->apihost;
}
/**
* @param mixed $apihost
*/
public function setApihost($apihost)
{
$this->apihost = $apihost;
}
/**
* @return mixed
*/
public function getApiuser()
{
return $this->apiuser;
}
/**
* @param mixed $apiuser
*/
public function setApiuser($apiuser)
{
$this->apiuser = $apiuser;
}
/**
* @return mixed
*/
public function getApipass()
{
return $this->apipass;
}
/**
* @param mixed $apipass
*/
public function setApipass($apipass)
{
$this->apipass = $apipass;
}
var $result;
/** @var \MBApiClient */
var $apiClient;
var $defaultErrorResponse;
var $defaultSuccessResponse;
public function __construct($inputObj = false, $outputJson = true, $autorun = false)
{
$this->defaultErrorResponse = array(
'code' => 400,
'status' => 'error'
);
$this->defaultSuccessResponse = array(
'code' => 200,
'status' => 'success'
);
$this->outputJson = $outputJson;
if ($autorun) {
$this->__init();
$this->process($inputObj);
}
}
public function __init() {
$this->apiClient = new MBApiClient($this->getApihost(), $this->getApiuser(), $this->getApipass());
}
public function process($inputObj = null, $context)
{
$response = false;
$methodeName = false;
$obj = null;
$defaultSuccessResponse = $this->defaultSuccessResponse;
$defaultErrorResponse = $this->defaultErrorResponse;
try {
$obj = $this->prepare($inputObj);
$methodeName = 'listener' . ucfirst($obj->task);
if (is_object($obj) && method_exists($this, $methodeName)) {
try {
$responseOfMethod = $this->$methodeName($obj->payload, $context);
$response = $responseOfMethod;
// $response = $responseOfMethod + $defaultSuccessResponse; //temp disabled
} catch (Exception $e) {
$defaultErrorResponse['code'] = 500;
$msg = $e->getMessage();
// debug info from curl
// \MBApiResponse::__construct
if (is_array($msgArray = json_decode($msg, true))) {
$defaultErrorResponse = $msgArray;
} else {
$defaultErrorResponse['message'] = 'MB Webhook says (methodeName: ' .$methodeName.'): ' . $e->getMessage() . ' - payload: '. print_r($obj->payload, true) . '- trace: ' . $e->getTraceAsString() . ' - code: ' . $e->getCode();
}
}
} else {
$defaultErrorResponse['message'] = 'Could not find method ' . $methodeName . ' - unknown Task: ' . $obj->task . "\n" . print_r($inputObj, true);
}
} catch (Exception $e) {
$defaultErrorResponse['message'] = 'MB Webhook says (task: ' .$obj->task.'): ' . $e->getMessage() . ' - payload: '. print_r($obj->payload, true);
}
$this->result = $response;
return $this;
}
public function prepare($inputObj = false)
{
if (is_object($inputObj)) {
$obj = $inputObj;
}
else {
$json = file_get_contents('php://input');
$obj = json_decode($json);
}
if (!is_object($obj)) {
throw new Exception('MBWebhook: malformed JSON: ' . file_get_contents('php://input'));
}
if (!is_string($obj->task) || !is_object($obj->payload)) {
throw new Exception('incomplete JSON - missing task or payload');
}
return $obj;
}
public function _result($response)
{
if ($this->outputJson) {
header('Content-Type: application/json; charset=utf-8');
$code = ($response['code']) ? $response['code'] : '200';
http_response_code($code);
echo json_encode($response);
exit();
}
return $response;
}
public function getResult()
{
return $this->result;
}
function _bulkResponseHandler($response)
{
// handle bulk action response
// summarize into a single response which will be protocolled in the task queue
if (sizeof($response->result->new) > 0) {
// successfully created
$result = array(); // default success result
} elseif (sizeof($response->result->success) > 0) {
// successfully updated
$result = array(); // default success result
} elseif (sizeof($response->result->invalid) > 0) {
// invalid data provided
$result = array(
'code' => 400, // override
'status' => 'error', // override
'message' => print_r(json_encode($response->result), true)
);
} elseif (sizeof($response->result->exists) > 0) {
// some items did already exists
$result = array(
'code' => 202, // override
'status' => 'warning', // override
'message' => print_r(json_encode($response->result), true)
);
} else {
// unknown situation
$result = array(
'code' => 400, // override
'status' => 'error', // override
'message' => print_r(json_encode($response->result), true)
);
}
return $result;
}
}