I am trying to implement a soaprequest and making the call does seem to work. The only problem is: I don't know how to receive the response data. My code looks like this:
$auth = array(
'UsernameToken' => array(
'Username' => 'xxx',
'Password' => 'yyyy'
)
);
$header = new SoapHeader('xs','Security',$auth, 0);
$client->__setSoapHeaders($header);
$client->__setLocation('http://example.com/test.php');
$params = array(
...
'trace' => 1,
'cache_wsdl' => 0
);
try {
$response = $client->getSomeData($params);
}catch(Exception $e){
echo "Exception: ".$e->getMessage();
}
print_r($response);
This results in an empty page, because $response is empty. But the test.php file is called (I tried with a simple mail() command and it sends the mail every time I call the page with the soapclient).
So I guess the soap response is somehow sent to the test.php file - right? How do I get it? If I do not set the location, I get a nullpointerexception, so I have to do that. I tried
$client->__getLastResponse()
that's empty too.
What can I do, how do I get the soap response data? Any hints would be appreciated. Thank you!
Related
I modified it all now I have this file that makes my api work.
auth.php:
<?php
include 'Unirest.php';
function login()
{
$headers = array('Accept' => 'application/json');
$data = array(
"grant_type" => "password",
"client_id" => "myclientid",
"client_secret" => "myclientsecret",
"username" => "username",
"password" => "password"
);
$response = Unirest\Request::post('http://i-scent.fr/api/oauth_token', $headers, $data);
// $response->code;
// $response->headers;
return $response->body->access_token;
}
function device_info($device_id,$token){
$header = array('Accept' => 'application/json',
'Authorization' => 'Bearer '.$token );
$response = Unirest\Request::get('http://i-scent.fr/api/devices/'.$device_id,$header);
echo $response->body->name;
echo "</br>";
}
function diffuse($device_id,$token,$duration,$intensity){
$header = array('Accept' => 'application/json', 'Authorization' => 'Bearer '.$token );
$data = array('time' => 1, 'percent' => 50);
$body = Unirest\Request\Body::form($data);
$response = Unirest\Request::put('http://i-scent.fr/app_dev.php/api/device/'.$device_id.'/actions/diffusion',$header,$body);
echo $response->code;
echo "</br>";
}
When I use all the functions in a simple script it works perfectly on my website. But when I put it like this in my webhook, I have error 500 internal server error. I have all the unirest libraries.
<?php
include "auth.php";
function processMessage($update) {
if($update["result"]["action"] == "sayHello"){
$token = login();
$name = device_info("1966",$token);
diffuse("1966",$token,"0.5","50");
sendMessage(array(
"source" => $update["result"]["source"],
"speech" => "bonjour webhook",
"displayText" => "bonjour webhook",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
echo json_encode($parameters);
}
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
if (isset($update["result"]["action"])) {
processMessage($update);
}
Error 500 is supposed to mean that the webhokk's script crashed somewhere but I don't know where and why.
Update 2
Based on your most recent code, you're including "auth.php", which works in the original environment (which is being called as part of a web page, it sounds like).
Your code has two functions, device_info() and diffuse(), which output their results instead of returning them. This output isn't JSON, and includes HTML markup. This is being sent as part of the result of your webhook and will cause what is returned to be invalid.
Update
Based on your latest code, there are still many logical, and a few syntactical, problems.
A "500 Internal Server Error" indicates that your program didn't run correctly and crashed for some reason. As posted, it is missing a closing }, which could be the problem if that isn't in your actual code.
Even if you fix that, there are many issues with the code:
It isn't clear what you intend to do with the results of calling your "test1" script. You store them in $data and don't do anything with it.
You're calling the other website (test1) before you look at what the user has asked you to do. Which is fine, but then why do you care what the user is asking you?
Original Answer
There are a few errors here, but the underlying problem is that you're mixing up where things run and the capabilities of the caller to your webhook.
For a Dialogflow webhook, Google/Dialogflow is sending JSON (which you seem to be handling ok), and expecting back JSON. Although it looks like you send this back as part of send_message(), you're also sending something back when you call connexion(). What you're sending back in this case is not JSON, but HTML with JavaScript.
Which leads to the second problem - If this was php that was generating an HTML page that included a script, you'd be in fine shape. But it isn't. You have to send back only JSON.
You can do something like this to call the other API and get back the contents:
$body = file_get_contents("http://google-home.exhalia.fr/test1");
Which will set $body to the body of the page you've called. What you do with that, at that point, is up to you. But you need to make this call before your call to send_message() because you want to represent the contents as part of what you're saying.
(See How to send a GET request from PHP? for a discussion of other methods available to you in case you need to do a POST, use header information, etc.)
I am trying to connect my script to the SOAP client. But when I try to do it throws the mentioned error. When I tried to get the function with
$client->__getFunctions(). It shows all the function. when I try to call them it ends in fatal error.
$client = new SoapClient("http://bsestarmfdemo.bseindia.com/MFOrderEntry/MFOrder.svc?singleWsdl",array(
'soap_version' => SOAP_1_2, // !!!!!!!
));
var_dump($client->__getFunctions());
//var_dump($client->__getTypes());
$login_params = array(
'UserId' => 123456,
'Password' => 123456,
'PassKey' => 1234569870,
);
//$response = $client->getPassword($login_params);
$response = $client->__soapCall('getPassword', array($login_params));
dd($response);
if i change the SOAP version to 1.1 i get another error Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'. Would be great if i come to know what i am missing here.
To address the reply made by #Naveen Kumar: this was my solution.
// Apply WSA headers
$action = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'Action', self::ACTION_PREFIX.$this->action);
$to = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'To', $this->endpoint);
$this->client()->__setSoapHeaders([$action, $to]);
In the end, $this->client simply returns an instance of \SoapClient and the action contains the full URL to the method. Naturally, the To portion is optional, but in my case it obviously points towards the endpoint specified in the .wsdl file.
I'm trying to make a soap call to a server with as little code as possible. But I'm alreaty having issues authenticating myself (No headers neccessary for that call). This is the code I have:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: text/html; charset=utf-8');
$data = array('Username' => 'someusername', 'Userpass' => 'somepass');
try
{
$client = new SoapClient(null, array(
"location" => "http://relaxdays.plentymarkets-x1.com/plenty/api/soap/version115/?xml",
"uri" => "http://relaxdays.plentymarkets-x1.com/plenty/api/soap/version115/",
"trace" => true,
"soap_version" => SOAP_1_1,
"exceptions" => false
));
$response = $client->__soapCall("PlentySoapRequest_GetAuthentificationToken", $data);
}
catch (Exception $e)
{
echo "Error!";
echo $e -> getMessage();
echo '<br/><br/>Last response:<button type="button" onclick="if(document.getElementById(\'spoiler1\').style.display==\'none\') {document.getElementById(\'spoiler1\') .style.display=\'\'}else{document.getElementById(\'spoiler1\') .style.display=\'none\'}">Show/Hide</button><div id="spoiler1" style="display:none; font-family:monospace;">'. htmlspecialchars($client->__getLastResponse()).'</div>';
}
echo '<br/><br/>Last request:<button type="button" onclick="if(document.getElementById(\'spoiler2\').style.display==\'none\') {document.getElementById(\'spoiler2\') .style.display=\'\'}else{document.getElementById(\'spoiler2\') .style.display=\'none\'}">Show/Hide</button><div id="spoiler2" style="display:none; font-family:monospace;">'. htmlspecialchars($client->__getLastRequest()).'</div>';
echo '<br/><br/>Response:<button type="button" onclick="if(document.getElementById(\'spoiler3\').style.display==\'none\') {document.getElementById(\'spoiler3\') .style.display=\'\'}else{document.getElementById(\'spoiler3\') .style.display=\'none\'}">Show/Hide</button><div id="spoiler3" style="display:none; font-family:monospace;">'. htmlspecialchars($response).'</div>';
?>
However, regardless of what I try, it doesn't seem to work. The furthest I've come is this error:
SoapFault exception: [VersionMismatch] Wrong Version in /var/www/htdocs/plentyimport/tester.php:18
Stack trace: #0 /var/www/htdocs/plentyimport/tester.php(18): SoapClient->__soapCall('PlentySoapReque...', Array) #1 {main}
I've already tried using "soap_version" => SOAP_1_2, or switching the Soap-URL to different versions (eg. /version112/) but the error just does not want to go away.
Any help would be appreciated.
Thank you very much
virhonestum
You have to pass the definition of SOAP as first parameter, like this:
$client = new SoapClient('http://relaxdays.plentymarkets-x1.com/plenty/api/soap/version115/?xml');
I have stripped other arguments as those are not required for making this work.
The call should be made to operation, in this case like this:
$response = $client->__soapCall("GetAuthentificationToken", $data);
An finally, the data should contain structure PlentySoapRequest_GetAuthentificationToken, like this:
$data = [
'PlentySoapRequest_GetAuthentificationToken' => [
'Username' => 'someusername',
'Userpass' => 'somepassword'
]
];
Note: I'm not posting this as complete answer. I don't know SOAP and can't explain what was wrong and how I fixed it, only posting this to help author get out of this phase.
I'm new to Laravel framework so I'm having a hard time to do something very trivial. The main idea is to contact an API and get its response. Below is my function where I'm having error,
public function verification($id=null){
try{
$res = $client->createRequest('POST','http://35.161.181.102/api/socialverify/linkedin',['headers' => $headers , 'body' => $urlclean]);
$res= $client->send($res);
}catch(\GuzzleHttp\Exception\RequestException $e) {
\Log::info($e->getMessage());
\Log::info($e->getCode());
\Log::info($e->getResponse()->getBody()->getContents());
}
}
When I run the above function I'm getting the error shown below,
Illegal string offset 'id'
Any pointers on what I'm doing wrong and how can I solve it.
Any help is appreciated. Thank in advance.
What do you see in your /storage/logs/laravel.log?
I assume Client is Guzzle Client and by default Guzzle throws RequestException whenever there is a request issue. See Documentation. So why not try to do this and see what's the error responded from Guzzle:
try {
$response = $client->post('http://link-to-my-api', array(
'headers' => array('Content-type' => 'application/json'),
'body' => $data
));
$response->send();
}catch(\GuzzleHttp\Exception\RequestException $e) {
\Log::info($e->getMessage());
\Log::info($e->getCode());
\Log::info($e->getResponse()->getBody()->getContents());
}
And check your /storage/logs/laravel.log to see the logs being printed.
you can try this way:
use Illuminate\Support\Facades\Http;
$response = Http::withHeaders($header)
->post($url, [
$data
]);
I connected to a SOAP server from a client and am trying to send form information back.
The connection works, but I have no idea how to send data back. I have received documentation ( -> http://s000.tinyupload.com/?file_id=89258359616332514672) and am stuck at the function AddApplication
This is the PHP code I've written so far. There is no form integration yet, only dummy data.
<?
$client = new SoapClient(
'https://wstest.hrweb.be/TvBastards/TvBastards/Job.svc?singleWsdl',
array(
'soap_version' => SOAP_1_1
)
);
$params = array(
'username' => 'XXX',
'password' => 'XXX',
'environmentKey' => 'XXX',
);
//Open session
try{
$token = $client->OpenSession($params);
}catch(SoapFault $ex){
echo "<pre>";
print_r($ex->detail->ExceptionDetail);
echo "</pre>";
}
//Add Application
try{
$resp = $client->AddApplication($params, ___THE_XML_SHOULD_BE_HERE___); // I have no idea how I can implement a XML file over here, and make this part work
}catch(SoapFault $ex){
echo "<pre>";
print_r($ex->detail->ExceptionDetail);
echo "</pre>";
}
//Close session
try{
$app = $client->CloseSession($token);
}catch(SoapFault $ex){
echo "<pre>";
print_r($ex);
echo "</pre>";
}`
The error I receive now is the following:
End element 'Body' from namespace 'http://schemas.xmlsoap.org/soap/envelope/' expected. Found element 'param1' from namespace ''. Line 2, position 156.
Which is understandable as I don't provide any XML.
I receive my token so the OpenSession works perfectly. As said, I'm completely stuck at the AddApplication function. This is my first encounter with a SOAP service, so every possible bit of explanation is highly appreciated.
Fixed it, and hopefully it can help out some others. I'll try and put it into steps.
define('SIM_LOGIN', 'LOGIN NAME HERE');
define('SIM_PASSWORD', 'LOGIN PASSWORD HERE');
define('ENV_KEY', 'ENVIRONMENT KEY HERE');
/*** login parameters ***/
$params = array(
'username' => SIM_LOGIN,
'password' => SIM_PASSWORD,
'environmentKey' => ENV_KEY,
);
/*** Set up client ***/
$client = new SoapClient(
__SOAP URL HERE__,
array(
'soap_version' => SOAP_1_1
)
);
After setting up the parameters and connecting to the client, we can start calling functions within the SOAP service. Every SOAP service will be different, so function names and parameters can be different. In below example I need to open a session to retrieve a token. This token is used in all the other functions, so this function is necessary. If something fails I call the "abort()" function.
try{
$token = $client->OpenSession($params);
}catch(SoapFault $ex){
abort();
}
If the token is received I call upon the function AddApplication. This expects the token parameter and an "object" (which is basically an STDClass).
I create an stdClass with all my data:
/*** Create stdClass with requested data ***/
$std = new stdClass();
$std->Firstname = $firstname;
$std->Lastname = $lastname;
$std->Birthdate = $birthdate;
$std->Phone = $phone;
$std->Email = $email;
Be sure to check camelcasing of names or capitals, as this makes all the difference.
Now we call upon the AddApplication function with parameters "token(string)" and "application(object)".
/*** AddApplication ***/
try{
$result = $client->AddApplication(array("token" => $token, "application" => $std));
}catch(SoapFault $ex){
abort();
}
If all goes well the data is stored on the external server and you receive a "success" message. It's possible that you receive a "fail" even without going into the SoapFault. Be sure to log both "$result" and "$ex", as a SOAP service can return a "Fail" but the try-catch sees this as a well formed result.
Last thing to do is close the session (and destroy the token)
/*** CloseSession ***/
try{
$app = $client->CloseSession($token);
}catch(SoapFault $ex){
abort();
}
If any questions, don't hesitate to ask them here, I'll be glad to help as I had such problems figuring this out.