How to get webhook response data - php

I'm still new to webhook. What I need to do here is to do a callback whenever there's a new registration on the registration platform called Bizzabo. This platform has provided Webhook integration by having us putting the Endpoint URL and select which action that will trigger the Webhook. I've also used Request Bin and it displays the data well.
However, how can I echo the JSON body data like how it displayed in Request Bin in my interface URL php?
This is how the Webhook integration looks like on Bizzabo
Data captured from Webhook when tested using Request Bin
Thank you!

Your need an endpoint which receives the callback instead Request Bin, then access it in the following way using file_get_contents('php://input') and json_decode()
For example http://example.com/bizzabo-callback-handler.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// decode json
$object = json_decode($json);
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
die(header('HTTP/1.0 415 Unsupported Media Type'));
}
/**
* Do something with object, structure will be like:
* $object->accountId
* $object->details->items[0]['contactName']
*/
// dump to file so you can see
file_put_contents('callback.test.txt', print_r($object, true));
}

If the data receiving in compressed format(gzip) use gzdecode :
<?php
if (!function_exists('gzdecode')){
function gzdecode($data){
// strip header and footer and inflate
return gzinflate(substr($data, 10, -8));
}
}
// get compressed (gzip) POST request into a string
$comprReq = file_get_contents('php://input');
// get decompressed POST request
$decomprReq = gzdecode($comprReq);
// decode to json
$jsonData = json_decode($decomprReq, true);
// do your processing on $jsonData
?>

Related

why i am not able to print request in YII rest api using postman

I am making rest API with Yii Plus when I am trying to print_r request (using Postman) it's empty, can anyone let me know what I am doing wrong.
<?php
namespace frontend\controllers;
use Yii;
use yii\rest\Controller;
class ApiController extends Controller
{
Const APPLICATION_ID = 'ASCCPE';
private $format = 'json';
public function actionUserRegister()
{
$request = \Yii::$app->request->post(); $post = (file_get_contents("php://input"));
print_r($request);
die('sdw');
}
}
Output
You are not trying to print request. You are trying to print post data, but you are not sending any post data by your request.
The \Yii::$app->request->post(); returns data from $_POST array. This array is filled from request body only for data that have been sent in form-data or x-www-form-urlencoded format.
In postman click open the body part of request, select one of the two mentioned formats and fill the data you want to send.
If you want to use other format for request, like json or xml, you have to read it from php://input. You already have it in your code:
$post = (file_get_contents("php://input"));
So try to print the $post instead of $request variable. But you still need to fill the body part of request in postman.
The params you've set in postman are the GET params. Those are part of request's url. You can get them for example like this:
$request = \Yii::$app->request->get();
You are returning with the message in the die function.
Instead of this you can try this way:
die(print_r($request, true));
Example:
public function actionCreate()
{
$request = Yii::$app->request->post();
die(print_r($request, true));
}
better:
return print_r($request, true);
Example:
public function actionCreate()
{
$request = Yii::$app->request->post();
return print_r($request, true);
}
better:
// include the VarDumper class
\Yii::info(VarDumper::dumpAsString($request));
// output will be located in your app.log file
More info on the print_r function
Example:
public function actionCreate()
{
return Yii::$app->request->getBodyParams();
}

gwt: send php post request

I am trying to communicate to a php server from my gwt project.
I already got a GET request to work, however, my POST request doesn't work so far.
Here's my code:
Button synchronize = new Button("synchronize ",
new ClickHandler() {
public void onClick(ClickEvent event) {
String myurl = URL
.encode("php/test.php");
RequestBuilder builder = new RequestBuilder(
RequestBuilder.POST, myurl);
JSONObject jsonValue = new JSONObject();
jsonValue.put("name", new JSONString("Abc"));
builder.setHeader("Content-Type", "application/json");
try {
Request request = builder.sendRequest(jsonValue.toString(),
new RequestCallback() {
public void onError(Request request,
Throwable exception) {
processResponse("ERROR");
}
public void onResponseReceived(
Request request,
Response response) {
if (200 == response.getStatusCode()) {
processResponse(response
.getText());
} else {
processResponse("ERROR");
}
}
});
} catch (RequestException e) {
processResponse("ERROR");
}
}
});
public void processResponse(String responseString) {
Window.alert(responseString);
}
I can see that the post request goes out and the request payload is a json-object. However, when I try to access the data in the php script, I get the error that the index name is undefined.
Here's the PHP:
<?php
echo $_POST["name"];
?>
Is there something wrong with my PHP?
Does anyone have a working example for this?
While I haven't checked the PHP documentation so far, I tend to remember, that $POST contains the post request's variables, especially useful in a x-www-form-urlencoded request. .. Checked it, yes. I am right :-)
What you actually want is to read the body of the post request and parse it's JSON content to a PHP array or hash.
To read the body see here: How to get body of a POST in php?
$entityBody = file_get_contents('php://input');
Parsing json is described here: Parsing JSON file with PHP
I will not quote the code from there, as it maybe does not exactly fit your needs, but you look for json_decode($json, TRUE).

Guzzle 6: no more json() method for responses

Previously in Guzzle 5.3:
$response = $client->get('http://httpbin.org/get');
$array = $response->json(); // Yoohoo
var_dump($array[0]['origin']);
I could easily get a PHP array from a JSON response. Now In Guzzle 6, I don't know how to do. There seems to be no json() method anymore. I (quickly) read the doc from the latest version and don't found anything about JSON responses. I think I missed something, maybe there is a new concept that I don't understand (or maybe I did not read correctly).
Is this (below) new way the only way?
$response = $client->get('http://httpbin.org/get');
$array = json_decode($response->getBody()->getContents(), true); // :'(
var_dump($array[0]['origin']);
Or is there an helper or something like that?
I use json_decode($response->getBody()) now instead of $response->json().
I suspect this might be a casualty of PSR-7 compliance.
You switch to:
json_decode($response->getBody(), true)
Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.
I use $response->getBody()->getContents() to get JSON from response.
Guzzle version 6.3.0.
If you guys still interested, here is my workaround based on Guzzle middleware feature:
Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:
<?php
namespace GuzzleHttp\Psr7;
class JsonAwareResponse extends Response
{
/**
* Cache for performance
* #var array
*/
private $json;
public function getBody()
{
if ($this->json) {
return $this->json;
}
// get parent Body stream
$body = parent::getBody();
// if JSON HTTP header detected - then decode
if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
return $this->json = \json_decode($body, true);
}
return $body;
}
}
Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:
<?php
$client = new \GuzzleHttp\Client();
/** #var HandlerStack $handler */
$handler = $client->getConfig('handler');
$handler->push(\GuzzleHttp\Middleware::mapResponse(function (\Psr\Http\Message\ResponseInterface $response) {
return new \GuzzleHttp\Psr7\JsonAwareResponse(
$response->getStatusCode(),
$response->getHeaders(),
$response->getBody(),
$response->getProtocolVersion(),
$response->getReasonPhrase()
);
}), 'json_decode_middleware');
After this to retrieve JSON as PHP native array use Guzzle as always:
$jsonArray = $client->get('http://httpbin.org/headers')->getBody();
Tested with guzzlehttp/guzzle 6.3.3
$response is instance of PSR-7 ResponseInterface. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces
getBody() returns StreamInterface:
/**
* Gets the body of the message.
*
* #return StreamInterface Returns the body as a stream.
*/
public function getBody();
StreamInterface implements __toString() which does
Reads all data from the stream into a string, from the beginning to end.
Therefore, to read body as string, you have to cast it to string:
$stringBody = $response->getBody()->__toString()
Gotchas
json_decode($response->getBody() is not the best solution as it magically casts stream into string for you. json_decode() requires string as 1st argument.
Don't use $response->getBody()->getContents() unless you know what you're doing. If you read documentation for getContents(), it says: Returns the remaining contents in a string. Therefore, calling getContents() reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.
Adding ->getContents() doesn't return jSON response, instead it returns as text.
You can simply use json_decode

How to set the content type of flight framework response

I am writing a restful webservice for my android app, and i am using flight php framework to route url. i have written a simple code shown below to return a json payload posted to the server instead it returns an html content type instead of a json. Please guys how to i change the response content-type to json, thanks in advance.
My code here:
include ('lib/flight/autoload.php');
include ('TestClass.php');
use flight\Engine;
$app = new Engine();
$app->_route('/', 'hello');
$app->_route('/user', array('TestClass', 'hello'));
$app->_start();
function hello(){
$request = Flight::request()->getBody();
echo json_encode($request);
}
#julianm is almost correct.
Flight::json($response);
But echo function is not needed.
source: http://flightphp.com/learn#json
header( "Content-type: application/json" );
echo json_encode( $request );
To send a JSON response with FlightPHP, you can use something like:
$response = array('id'=>1, 'website'=>'http://slidehunter.com');
echo Flight::json($response);

API Request $_POST returning empty array

I'm using Zurmo and trying to create a new account using REST API. I followed this documentation precisely: http://zurmo.org/wiki/rest-api-specification-accounts to pass the required parameters as json array.
This is my php code:
public function actionCreateOrUpdate()
{
$params=$_POST;
$modelClassName=$this->getModelName();
foreach ($params as $param)
{
if (!isset($param))
{
$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);
}
$r=$this->GetParam($param);
$res= array('status' => 'SUCCESS', 'data' => array($r));
print_r(json_encode($res,true));
}
}
function GetParam ($param){
$modelClassName=$this->getModelName();
if (isset($param['mobile_id'] ) && !$param['mobile_id']=='' &&!$param['mobile_id']==null)
{ $id=$param['mobile_id'];
$params=array();
foreach ($param as $k => $v) {
if(!($k=='mobile_id')) {
$params[$k] = $v;}
}
if ($params=null){$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);}
$tableName = $modelClassName::getTableName();
$beans = ZurmoRedBean::find($tableName, "mobile_id = '$id'");
if (count($beans) > 0)
{
$result = $this->processUpdate($id, $params);
}else{
$result = $this->processCreate($params,$id);
}
}
return $result;
}
The problem is that the $_POST method is returning an empty array. While debugging I tried to use print_r($_POST) and it also returned an empty array. I also tried to pass parameters as plain text and got the same result. I tried $_GET method and it worked. I think the problem is in the $_POST method, maybe I need to change something in my .php files. Any ideas please?
You should first hit the api with static data, to check if it works fine, then try to integrate php within that static data. You will need to read the documentation for which action accepts which format, and which method is supported(GET OR POST). Then try die(); , before sending if the array formed is as per the documentation.
I had similar issue when creating Account using REST API from java client. The problem was I did not send the proper POST request.
Another symptom also was on server side print_r(file_get_contents("php://input"),true); php code returned the correct request data.
Specifically the root cause was:
The Content-Type HTTP header was not "application/x-www-form-urlencoded"
The value field value in POST request was not properly encoded ( I used java.net.URLEncoder.encode method to overcome this)
After fixing these it worked.

Categories