How can I get headers sent by GuzzleHttp\Client()->get('URL')?
I can only get response headers, but not request. Help! thanks.
You can call the getHeaders() method of Request to get all the headers in a request, if you want to specifically check for a header you can use hasHeader()
use GuzzleHttp\Psr7;
$request = new Psr7\Request('GET', 'URL', ['Foo' => 'Bar']);
//Check for a header
if ($request->hasHeader('Foo')) {
echo 'Yes.';
}
//Get all the headers
foreach ($request->getHeaders() as $name => $values) {
echo $name .': ' . implode(', ', $values) . "\r\n";
}
Related
I am trying to set up a webhook from callrails platform. According to CallRail documentation it appears that my endpoint should response with a HTTP status code of 200? I've done webhooks before but never seen this one before. I am not getting anything after a call is made.
From call rails docs
"Your endpoint should respond with a HTTP status code of 2xx to indicate that the data was received properly. In general, a response status code other than 2xx indicates that the webhook was unable to complete the requested action."
This is the php code I am using. I just want to see the data being posted. Is there something I need to add to properly respond with 200 status code?
include('common.php');
if(!empty($_POST))
{
foreach($_POST as $key => $value)
{
$msg .= 'Key: ' . $key . ' => ' . $value . '<br>';
}
$ret = runner_mail(array('to' => 'xxxx', 'subject' => 'Callrail Call POST', 'htmlbody' => $msg));
$data = json_decode($_POST['body'], true);
if(!empty($data))
{
foreach($data as $key => $value)
{
$message .= 'Key: ' . $key . ' => ' . $value . '<br>';
}
$ret = runner_mail(array('to' => 'xxxxxx', 'subject' => 'Callrail Body Data', 'htmlbody' => $message));
}
}
Thanks for your feedback
for anyone that wants to know here is the answer.
$payload = #file_get_contents('php://input');
$call = json_decode($payload);
//process data
http_response_code(200);
How can I create an asynchronous request to multiple URI with different post data for each?
I am able to get the data for each of the URI, but I want to make it asynchronous.
Also, how do I timeout if the request takes too long?
My code:
//url
$ur1 = 'www.exaample1.com';
$ur2 = 'www.Test.com';
//xml
$ur1_xml = ''; // xml code
$ur2_xml = ''; // xml code
//headers
$ur1_header = array("POST HTTP/1.1",
"Content-type: application/xml; charset=\"utf-8\"",
"Content-length: " . strlen($ur1_xml));
$ur2_header = array("POST HTTP/1.1",
"Content-type: application/xml; charset=\"utf-8\"",
"Content-length: " . strlen($ur2_xml));
$client = new Client();
// make request
$request = new Request('POST', $ur1_url, $ur1_headers,$ur1_xml);
$promise = $client->sendAsync($request)->then(function ($response) {
echo '<pre>';
print_r(simplexml_load_string($response->getBody()));
echo '</pre>';
});
die();
For application/x-www-form-urlencoded send Async requests you can get benefit from Guzzle promises. Headers and POST fields should go into an array as documents state.
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
.
.
.
$client = new Client();
$promises = [
$client->postAsync($url1, ['headers' => $headers1, 'form_params' => $postData1]),
$client->postAsync($url2, ['headers' => $headers2, 'form_params' => $postData2]),
$client->postAsync($url3, ['headers' => $headers3, 'form_params' => $postData3])
];
$results = Promise\unwrap($promises);
$results = Promise\settle($promises)->wait();
// response headers of first request
print_r($results[0]['value']->getHeaders());
// retrieved contents of second request
echo $results[1]['value']->getBody()->getContents();
Following is the code I am using.
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
function handle_response($output, $response){
if($output['status'] === "failed"){
$response = $response->withStatus(400);
$response->getBody()->write(json_encode($output));
}
else{
$response->getBody()->write(json_encode($output));
}
return $response;
}
/* user profile */
$app->get('/user/profile', function (Request $request, Response $response) {
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
$name . ": " . implode(", ", $values);
}
if ($request->hasHeader('Authorization')) {
$output['token'] = 'yes';
}
else
$output['token'] = $name;
$output['status'] = "success";
return handle_response($output, $response);
});
I am using postman in google chrome to test this REST service.
I am passing a custom header "Authorization" along with the GET request.
however, this program doesn't recognize any custom headers.
The code block
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
$name . ": " . implode(", ", $values);
}
only returns the header "HTTP_ACCEPT_LANGUAGE".
Please help me to figure out, what went wrong here.
It is not Slim, it is considered a PHP feature. If you are sending something else than valid HTTP Basic Authorization header, PHP will not have access to it. You can work around this by adding the following rewrite rule to your .htaccess file.
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Another way is to use apache_request_headers() but it is Apache specific and not portable.
$oauth->getAccessToken() causes Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect).
How do I look at the request headers to figure out what exactly is wrong?
$oauth = new OAuth(CONSUMER_KEY, CONSUMER_SECRET);
$oauth->disableSSLChecks();
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
if($request_token_response === FALSE) {
throw new Exception("Failed fetching request token, response was: " . $oauth->getLastResponse());
} else {
$request_token = $request_token_response;
var_dump($request_token);
if (!isset($_GET['oauth_verifier'])) {
$this->redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" . $request_token['oauth_token']);
} else {
$oauth_verifier = $_GET['oauth_verifier'];
$oauth->setToken($request_token['oauth_token'], $request_token['oauth_token_secret']);
$access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken';
$access_token_response = $oauth->getAccessToken($access_token_url, "", $oauth_verifier);
if($access_token_response === FALSE) {
throw new Exception("Failed fetching request token, response was: " . $oauth->getLastResponse());
} else {
$access_token = $access_token_response;
$params = array();
$headers = array();
$method = OAUTH_HTTP_METHOD_GET;
// Specify LinkedIn API endpoint to retrieve your own profile
$url = "http://api.linkedin.com/v1/people/~";
// By default, the LinkedIn API responses are in XML format. If you prefer JSON, simply specify the format in your call
// $url = "http://api.linkedin.com/v1/people/~?format=json";
// Make call to LinkedIn to retrieve your own profile
$oauth->fetch($url, $params, $method, $headers);
echo $oauth->getLastResponse();
}
}
}
}
oauth_verifier only verifies the request_token from which it was obtained. I needed to store the original request_token in session instead of getting a new request_token on callback.
I am going crazy starting off with Web Services. I am trying to call the following WSDL using PHP and keep getting nowhere:
http://webservices.sabre.com/wsdl/sabreXML1.0.00/usg/SessionCreateRQ.wsdl
I found the following piece of code on the net, from someone with similar problems, but I could not get it to work either:
$soap = new SoapClient('http://webservices.sabre.com/wsdl/sabreXML1.0.00/usg/SessionCreateRQ.wsdl',
array(
'trace' => true,
'soap_version' => SOAP_1_2,
"exceptions" => 0));
$eb = new EbXmlMessage();
$sec = new Security();
$scrq = new SessionCreateRQ();
try {
$omg = $soap->SessionCreateRQ($scrq, $sec,$eb);
}
catch (Exception $e)
{
print_r($e);
}
//debug
print "Request: \n".
htmlspecialchars($soap->__getLastRequestHeaders()) ."\n";
print "Request: \n".
htmlspecialchars($soap->__getLastRequest()) ."\n";
print "Response: \n".
$soap->__getLastResponseHeaders()."\n";
print "Response: \n".
$soap->__getLastResponse()."\n";
print_r($omg);
//the first envelope headers
class EbXmlMessage
{
public $From = array('PartyId' => 'mysite.com');
public $To = array('PartyId' => 'myprovider.com');
public $CPAId = 'ZZZZ';
public $ConversationId = 'myconv#id.com';
public $Service = 'Session';// or SessionCreate?
public $Action = 'SessionCreateRQ';
public $MessageData = array(
'MessageId' => 'messageid',
'Timestamp' => '2009-04-18T15:15:00Z');
}
//the security token
class Security {
public $Username = "xxxxx";
public $Password = "yyyyy";
public $Organization = "ZZZZ";
public $Domain = "DEFAULT";
}
//this is suppoused to be the payload, or the xml i need to send at the end
class SessionCreateRQ
{
public $POS = array(
'Source' => array(
'_'=>"",
'PseudoCityCode'=>'ZZZZ'
));
}
I keep getting the following error:
Response:
HTTP/1.1 500 Internal Server Error
SOAPAction: ""
Content-Type: text/xml;charset=utf-8
Date: Sun, 19 Apr 2009 22:21:34 GMT
Connection: close
Server: SWS
Response:
soap-env:Client.InvalidEbXmlMessageUnable to internalize
messagejavax.xml.soap.SOAPException: Unable to internalize message at
com.sun.xml.messaging.saaj.soap.MessageImpl.(MessageImpl.java:135)
at
com.sun.xml.messaging.saaj.soap.MessageFactoryImpl.createMessage(MessageFactoryImpl.java:32)
at
com.sabre.universalservices.gateway.control.SoapProcessor.getRequest(SoapProcessor.java:263)
at
com.sabre.universalservices.gateway.control.WSGateway.handleRequest(WSGateway.java:380)
at
com.sabre.universalservices.gateway.control.WSGateway.doPost(WSGateway.java:306)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at
org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
at
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
at
org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
at java.lang.Thread.run(Thread.java:595) Caused by:
javax.xml.soap.SOAPException: Invalid
Content-Type:application/soap+xml at
com.sun.xml.messaging.saaj.soap.MessageImpl.verify(MessageImpl.java:159)
at
com.sun.xml.messaging.saaj.soap.MessageImpl.(MessageImpl.java:91)
... 19 more
SoapFault Object (
[message:protected] => Unable to internalize message
[string:private] => .....
This service should be validating me on the system and returning a security object to be used in later calls - a string(?) which I can then store in a session variable for the following calls.
Any help GREATLY appreciated!!!
One thing I noticed is that there is a faultcode value in the SoapFault Object:
[faultcode] => soap-env:Client.InvalidEbXmlMessage
So that may be a useful avenue to start debugging.
I tried comparing the structure of your EbXmlMessage to the XSD and the schema documentation, but I couldn't see any obvious reason that it was declared invalid.
Have you tried changing the Content-type header to text/xml?
Try using wsdl2php. It makes php classes out of the wsdl file. It uses php's SoapClient to send the data.
Here is a nice post explaining how to do it:
http://itworkarounds.blogspot.com/2011/10/simple-soap-client-with-wsdl2php-using.html
Just use nuSOAP. I don't like PHP native SoapClient. nuSoap generates for you a wsdl so you don't have to worry about how to make one.. Here's nuSOAP and here's a simple example code or you can download whole working code here :
Server :
<?php
// include the SOAP classes
require_once('nuSOAP/lib/nusoap.php');
function HelloWorld(){
return 'HelloWorld'; // Returns HelloWorld string
}
function Hello($name){
return 'Hello '.$name; // Returns Hello with name string parameter
}
// create the server object
$server = new nusoap_server();
// Initialize WSDL support
$server->configureWSDL('webservicenamespace', 'urn:webservicenamespace');
$server->register('HelloWorld', array(), array('result' => 'xsd:string')); //xsd:string; xsd:boolean; xsd:integer and so on..
$server->register('Hello', array('name' => 'xsd:string'), array('result' => 'xsd:string')); // array('parametername' => 'parametertype'),array('result' => 'returntype');
if (isset($error))
{
$fault =
$server->fault('soap:Server','',$error);
}
// send the result as a SOAP response over HTTP $HTTP_RAW_POST_DATA
$post = file_get_contents('php://input');
$server->service($post);
?>
Client :
<?php
// Pull in the NuSOAP code
require_once('nuSOAP/lib/nusoap.php');
// Create the client instance
$client = new nusoap_client('http://pathtourl/sample_webservice.php?wsdl', true);
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$result = $client->call('Hello', array('name' => 'Scott')); // Call function name, parameters;
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Display the request and response
echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
// Display the debug messages
echo '<h2>Debug</h2>';
echo '<pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
?>
Now when you want to make a client you need your wsdl you can simply get it by adding ?wsdl on your link i.e( webservice.php?wsdl )
Hope this helps :) Good luck with your web service.