Postman behavior different than HTTP plugin for PHP - php

I want to send a HTTP post request to my node.js server. I pass a JSON object as body (content type is set to application/json).
If I send -exactly- the same JSON object in the body via Postman (https://www.getpostman.com) it works perfectly! If I use this plugin here: https://github.com/Mashape/unirest-php it is not working, I get HTTP error 500 and error message 'Cannot read property '0' of undefined' like something would be wrong with my route/ my passed JSON.. which is definitely not the case because Postman works.
How can I fix this? Is there maybe a better PHP plugin that works as it should?
I hope somebody can help me.
//HTTP Requests an Node Server. Pfade entsprechend abändern sobald live
$teamsMemberOf = Unirest\Request::get("http://localhost:3001/members-matter/mm-teams/".$result['_id']."/get-teams");
$json = $teamsMemberOf->raw_body;
$buildJson = '{"team":'.$json.'}';
//$sendJsonEncoded = json_decode($buildJson, true);
$headers = array("Accept" => "application/json");
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/members-matter/mm-boxes/".$result['_id']."/get-relevant-boxes-amount", $headers, $buildJson);
//$relevantBoxesAmount = Unirest\Request::post("http://mockbin.com/echo?", $headers, $buildJson);
//$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/members-matter/mm-boxes/56954133596dc02d0695cb89/get-relevant-boxes-amount", $headers, $sendJsonEncoded);
echo $relevantBoxesAmount->code;
echo $relevantBoxesAmount->raw_body;

Related

I am uploading file using MS graph API with msgraph-sdk library but didn't getting http response code here is my code

here i used msgraph-sdk php library i am uploading file. everything is working proper even file also uploaded and getting proper response but didn't getting http status code. please help
$headers = array(
"Content-Length"=> $numBytes,
"Content-Range"=> $content_range
);
$uploadByte = $graph->createRequest("PUT", $graph_url)
->addHeaders($headers)
->attachBody($data)
->setReturnType(Model\UploadSession::class)
->setTimeout("10000")
->execute();
$arraydata = (array)$uploadByte->getProperties();
print_r($arraydata);
echo '</pre>';
$httpcode = (array)$uploadByte->getStatus();

How to Send File(pdf) from Local Computer to API Whatsapp (Chat-API)

Greatings,
Today i Want to Make some task to upload some pdf file using Chat-API whatsapp.
the task maybe I will Run on windows shell, but now I test it on PHP file.
I using the documentation like this
$to = 'myPhone';
$url = 'https://chat-apiurl?andtokenhere';
$imageLocation = 'http://localhost/chat-api/file.pdf';
$data = [
'phone'=> $to,
'body' =>$imageLocation,
'filename'=>"filepdf.jpg",
'caption'=>'test',
];
$send = json_encode($data);
$options = stream_context_create(['http' => [
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $send,
]
]);
// Send a request
$result = file_get_contents($url, false, $options);
echo $result;
?>
if i change the file to online url that's work fine, but when using local file I got the error on result like that
{"error":"Unsupported file type"}
I Have try to convert my file to base 64 but that's return error like this
{"sent":false,"message":"Message was not sent: empty body. Please provide message text in body parameter in JSON POST."}
and that's the way i convert to base64
$getExtension = explode(".",$imageLocation);
$base64 = 'data:image/'.$getExtension[1].';base64,'.file_get_contents($imageLocation);
can anyone help me to send the local file? or maybe have other way to do that. or other API?
Thankyou so much
I know the question was posted a long time ago, but I'll leave the answer in case anyone is looking for a solution.
$base64='data:image/'.$getExtension[1].';base64,'.file_get_contents($imageLocation);
for:
$base64='data:image/'.$getExtension[1].';base64,'.base64_encode(file_get_contents($imageLocation));

Slack Events PHP Response

I'm working on an integration between Slack and Filemaker utilizing PHP. I am successful in having the code create a record in Filemaker based on the json request, and also have no trouble returning the challenge key to Slack.
However, I'm having trouble passing the header response 200 OK to Slack, while passing the challenge back. It looks like it has to be one or the other.
I've tried to move the HTTP header to different areas in the code, but haven't had any success so far.
Here is the current code:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data["challenge"])) {
$body = $_SERVER['HTTP_X_SLACK_RETRY_REASON'];
require_once ('Filemaker.php');
//$body = file_get_contents('php://input');
$fm = new Filemaker();
$fm->setProperty('database', '');
$fm->setProperty('username', '');
$fm->setProperty('password', '');
$command = $fm->newPerformScriptCommand('PHP_RESPONSE', 'script', $body);
$result = $command->execute();
}
else {
header("Content-Type: text/plain");
header('X-PHP-Response-Code: 200', true, 200);
echo $data["challenge"];
}
?>
The result I expect is for the code to return the challenge code for Slack, while also returning an HTTP header of 200 OK.
Currently I can see I am receiving an error of "http_error" from Slack, which is what leads me to believe the problem is that the header is not being passed back successfully.
Any ideas on what is wrong, or suggestions on the right direction to proceed would be greatly appreciated.
The problem was occurring because for events slack doesn't send "challenge" as a parameter when sending events. It looks like echoing "challenge" is only needed when initially setting the URL for the events API.
I enclosed the challenge echo in a if statement that would only trigger if the challenge variable was present. After doing so the 200 OK was successfully passed.
Here is the code I used that solved the problem for me:
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data["challenge"])) {
$message = [
"challenge" => $data["challenge"]
];
header('Content-Type: application/json');
echo json_encode($message);
}
The documentation is actually a bit inconsistent on this topic. It claims you can respond the challenge in plan text, but the example shows it as x-www-form-urlencoded.
To be on the safe side try returning the challenge as JSON. That works perfectly for me. You also do not need to explicitly set the HTTP 200 code.
Example code:
$message = [
"challenge" => $data["challenge"]
];
header('content-type: application/json');
echo json_encode($message);

Setting correct content type for cURL to receive a response

I'm trying to create a relatively simple PHP endpoint for users to send requests to. I know that the endpoint is working because when I accessed it using cURL the parameters I sent to my database we're added. The problem however is that when I use
var_dump($response);
The page returns "NULL".
So the code is working fine, I just want to know how to print an error/success message
This is what I've tried so far on the endpoint
header("HTTP/1.1 200 OK");
header('Content-Type: text/plain');
echo 'Success message';
the full cURL code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => 'example=this'
);
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$response = json_decode($resp, true);
var_dump($response);
So how can I get the success message to properly show instead of "NULL"?
Test if your curl code returns something by testing: var_dump($resp). It looks like NULL comes from json_decode. You are not returning valid JSON from the endpoint.
php > var_dump(json_decode("Success message", true));
NULL
Try returning a json string such as:
php > echo json_encode("Success", true);
"Success"
Note the " around it. This encodes a json string. See the JSON spec for a reference on how to encode json. Best practice, if your return json, then run your content through json_encode().
Your curl code seems correct.

Does GAE support Plivo?

I've been trying to implement Plivo on my GAE server but I'm getting a 500 error.
I setup Plivo by using Plivo's Github PHP Helper Library. I saved that file as plivo.php on my test server. Then I added plivosend.php with the following code
<?php
if($_POST) {
require_once 'plivo.php';
$auth_id = "auth_id";
$auth_token = "auth_token";
$p = new RestAPI($auth_id, $auth_token);
// make sure all 3 params are valid
if(!empty($_POST['send_to_name']) && !empty($_POST['send_to_number']) && !empty($_POST['sender_name'])) {
$message = 'this message doesn't matter';
$plivo_url = 'https://glacial-harbor-8656.herokuapp.com/report';
// Send message
$params = array(
'src' => '15555555555', // Sender's phone number with country code
'dst' => $_POST['send_to_number'], // Receiver's phone number with country code
'text' => $message, // Your SMS text message
'url' => $plivo_url, // The URL to which with the status of the message is sent
'method' => 'POST' // The method used to call the url
);
// Send message
$response = $p->send_message($params);
// Print the response
$message_uuid = $response['response']['message_uuid'][0];
if(!empty($message_uuid)) {
echo '{"success":1,"message_uuid":' . $message_uuid . '"}';
}
else {
// todo log this?
echo '{"success":0,"error_message":"Message failed to send."}';
}
}
else {
echo '{"success":0,"error_message":"Message failed to send. Incorrect params."}';
}
}
?>
On my test server (just my website), this sends without any problems. When I put both plivo.php and plivosend.php on GAE, I get the following 500 error:
207.58.203.50 - - [21/Sep/2015:09:58:00 -0700] "POST /plivosend.php HTTP/1.1" 500 25 - "appname/1.0.2 (iPhone; iOS 9.0; Scale/2.00)" "appname-xxx.appspot.com" ms=4 cpu_ms=3 cpm_usd=0.000003 instance=00c61b117cd04d3645448a84e24daba9991882e1 app_engine_release=1.9.26
I have no idea why... The details are extremely limited.
Does anyone have a clue? Does GAE not support Plivo?
Google App Engine restricts many functions (necessary in order to be a massively auto-scaling application platform). One restriction is outbound HTTP requests (from your PHP code to external). Read about it here, HTTP Requests and cURL Support for details and options.

Categories