I cant figure this out so I'm hoping you can lend a hand.
I am creating a twilio app, and I'm including this entire file in a foreach loop. But it keeps breaking my loop and wont continue after it runs.
It works great, but the foreach this is included inside of will not continue after it runs.
Any ideas?
Thanks,
Nick
<?php
//shorten the URL
$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$ebay_url);
// Include the PHP TwilioRest library
require "twilio/twilio.php";
// Twilio REST API version
$ApiVersion = "2010-04-01";
// Set our AccountSid and AuthToken
$AccountSid = "removed";
$AuthToken = "removed";
// Instantiate a new Twilio Rest Client
$client = new TwilioRestClient($AccountSid, $AuthToken);
// make an associative array of server admins
$people = array(
"removed"=>"Nick",
//"4158675310"=>"Helen",
//"4158675311"=>"Virgil",
);
// Iterate over all our server admins
foreach ($people as $number => $name) {
// Send a new outgoinging SMS by POST'ing to the SMS resource */
// YYY-YYY-YYYY must be a Twilio validated phone number
$response = $client->request("/$ApiVersion/Accounts/$AccountSid/SMS/Messages",
"POST", array(
"To" => $number,
"From" => 'removed',
"Body" => 'Alert! '.$title.' found for '. $price. '. View the item here: '.$tinyurl,
));
if($response->IsError)
echo "Error: {$response->ErrorMessage}\n";
else
echo "Sent message to: {$response->ResponseXml->SMSMessage->To}\n";
}
?>
I think the problem is that you're doing a require inside the for loop. There are objects defined in that twilio library so the second time you require it, the classes get defined again and this throws an error.
If you have error_reporting(E_ALL) set then you'll see an exception to that effect in your output.
I would either change it to a require_once or move it out of the for loop.
I hope that helps.
Related
Here's my current code:
require_once '/pathtovendor/vendor/autoload.php';
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
use Microsoft\Graph\Http\GraphRequest;
$access_token = "My valid access token";
$graph = new Graph();
$graph->setAccessToken($access_token);
$reply = array( "Comment" => "My reply" );
$message_id = "Valid message ID";
if($graph->createRequest("POST", "/me/messages/".$message_id."/reply")
->attachBody($reply)
->execute()){
// I can get to this part OK. Message is replied to.
//This code doesn't work
$graph->createRequest("PATCH", "/me/messages/".$message_id)
->attachBody(array( "Subject" => "New Subject" ))
->execute();
}
I can run GET and POST requests which work, but I can't get PATCH to work this way. It continues to throw a 500 Internal Server Error. Any help is appreciated.
This is only supported on draft messages. From the documentation:
subject | String |
The subject of the message. Updatable only if isDraft = true.
The following properties can only be updated in draft messages:
bccRecipients
body
ccRecipients
internetMessageId
replyTo
sender
subject
toRecipients
from
I am using DIalogflow (api.ai) to create chat interfaces. I created a webhook from Dialogflow to a simple app containing a php script deployed on Heroku.
Therefore, I placed in the webhook form of Dialogflow the url of my Heroku app which resembles to this: https://my_heroku_app_name.herokuapp.com.
My ultimate goal is to fetch some data from a database (through the php script) and then feed Dialogflow with them. For now, I am only trying to connect the Heroku app (php script) with Dialogflow through a webhook.
The php script of the Heroku app is the following:
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'GET'){
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->metadata->intentName->text;
switch ($text) {
case 'Name':
$speech = "This question is too personal";
break;
default:
$speech = "Sorry, I didnt get that.";
break;
}
$response = new \stdClass();
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
Keep in mind the following:
$method is GET for some reason instead of POST as it is supposed to be from Dialogflow.
if you try to echo any of the variables $requestBody, $json or $text then nothing is printed.
I have tested that the if branch is executed and that the default branch is executed at switch.
Why my PHP script cannot "see" the webhook from DIaloflow and fetch the data from it so as to respond appropriately?
P.S. My question is not a duplicate of Valid JSON output but still getting error. The former is about the input of the php script whereas the latter is about the output of the php script. These two things do not necessarily constitute identical problems.
try to do something like this with some modification in your code.
First, I suggest you to use action instead of using intent name for switch case.
index.php
<?php
require 'get_wardinfo.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'wardinfo':
$param = $input["result"]["parameters"]["number"];
getWardInfo($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_wardinfo.php
<?php
require 'config.php';
function getWardInfo($param){
$wardinfo="";
$Query="SELECT * FROM public.wardinfo WHERE wardno=$param";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$wardinfo= "Here is details that you require: Name: " . $row["name"]. " --- Address: " . $row["address"]. " --- MobileNo: " . $row["contact"];
$arr=array(
"source" => "RMC",
"speech" => $wardinfo,
"displayText" => $wardinfo,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "Have some problem .",
"displayText" => "Have some problem .",
);
sendMessage($arr);
}
}
?>
It seems you know each parameter and all about dialogflow and how it works with PHP arrays and all still if you have confusion in above code or method kindly put a comment.
And I will suggest you don't go for Heroku directly first try it with ngrok it will make your local server live and put the URL as webhook in dialogflow and you can easily debug the errors and all.
I managed to connect Dialogflow to my php script on Heroku.
I made the following changes on my php script (on Heroku) and on Dialogflow which led to this result:
I replaced the condition if($method == 'GET') with the condition if($method == 'POST') so as to anticipate the POST request of Dialogflow.
Keep in mind that until I solved the whole problem I was not receiving any POST request but I GET request so I thought that the POST request from Dialogflow leads to GET request because of a webpage redirection which I could not really see at that moment.
I replaced $text = $json->metadata->intentName->text; with $text = $json->results->metadata->intentName; which was the right json parsing for retrieving the value of intentName. (I have published here the json request from Dialogflow but nobody noticed my mistake)
I published my bot on Dialogflow through its built-in web demo and on Slack. This may sound quite irrelevant but also one person on the Dialogflow forum stated that: "Maybe it should rementioned somewhere. that api.ai98 is not parsing any parameters/values/data to you service untill you bot is published!!" (See the second post here: https://discuss.api.ai/t/webhook-in-php-example/229).
I have php version 7.1 in my localhost. I have made changes in my php.ini file to run SOAP from my localhost.
I need to generate primary and secondary session token by passing login id and password to SOAP client API.
Once session token is authenticated it will return some rate chart. My code is generating session tokens. But when I am passing that token key to the next method in SOAP Client api its always giving me an error like "Invalid Session Token" or "Invalid Authentication". However the same tokens are working well in SOAP UI exe. I mean I have installed SOAP UI exe and by using wsdl "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl" and using method "Login" and "LookupRate" its working everything fine. The way i need that.
But whenever i am using that tokens in php localhost its always giving me an authentication error by SOAP Client.
I am sharing my code below.
$wsdl = "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl";
$client = new SoapClient($wsdl, array('trace' => true));
$params = array('loginOperation'=>array('loginId'=>'ryder_cnx1','password'=>'ryder1','thirdPartyId'=>'dl'));
$client->Login($params);
$data = $client->__getLastResponse();
$p = xml_parser_create();
xml_parse_into_struct($p, $data, $vals, $index);
xml_parser_free($p);
$token = [];
foreach ($vals as $key => $value) {
foreach ($value as $key1 => $value1) {
if($key1 == "value")
$token[] = $value1;
}
}
echo "Primary Token = ".$token[0];
echo "<br> Secondary Token = ".$token[1];
//echo "<br> Expiry Date = ".$token[2];
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
$namespace = 'http://www.tcore.com/TcoreTypes.xsd'; // I am not sure about this namespace. Whether its correct or not.
$header = new SoapHeader($namespace,'sessionHeader',$params_session,true);
$client->__setSoapHeaders($header);
$params_data = array('lookupRateOperations'=> array(
'equipment'=>'Vans',
'origin'=>array('postalCode'=>array('country'=>'US','code'=>'30004')),
'destination'=>array('postalCode'=>array('country'=>'US','code'=>'10001'))
));
try{
$result = $client->LookupRate($params_data);
print_r($result);
}catch (SoapFault $exception){
//or any other handling you like
print_r(get_class($exception));
enter code hereprint_r($exception);
}
if anybody have any idea, please share it with me.
Awaiting any response.
Thanks a lot in advance :)
I know this is very old, and most likely the OP figured it out. But in case anyone else comes along, I was able to get it working with two slight changes.
First,
$namespace = 'http://www.tcore.com/TcoreTypes.xsd';
Should be
$namespace = 'http://www.tcore.com/TcoreHeaders.xsd';
Second,
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
should be
$params_session = array(
"sessionToken"=> array(
"primary"=>base64_decode($token[0]),
"secondary"=>base64_decode($token[1])
)
);
The rest of my code is similar enough that if the above changes are made, it should work. I would also refrain from posting real usernames and passwords, btw.
I am running the following code, and it is showing me this error. Can someone tell me why is my xml giving a problem? When i run this in the browser I get:
XML Parsing Error: junk after document element
When I run this through Twiilio I get the following error
parserMessage Error on line 2 of document : Content is not allowed in prolog.
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
require "twilio-php-latest/Services/Twilio.php";
/* Set our AccountSid and AuthToken */
$AccountSid = "xxxxx";
$AuthToken = "xxxx";
include 'db.php';
$caller=$_REQUEST['From'];
/* Instantiate a new Twilio Rest Client */
$client = new Services_Twilio($AccountSid, $AuthToken);
$from= "+17864310795";
$student_number=substr($caller,1);
$db = new PDO("mysql:host=localhost;dbname=xxxx","xxxx","xxxx");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$studentData=getSingleStudentData($db,$student_number);
foreach($studentData as $key=>$val)
{
$student_id=$val['student_id'];
$phone=$val['phone_number'];
$status=$val['status'];
echo $student_id;
// find out last call successfully completed by the student
if($status==1)
{
$progress = getLastActivity($db,$student_id);
X
X
X
echo "done with initialize<br/>";
$server= "http://sample.com";
try {
$to = '+' . $phone;
echo $phone;
$questions_id_url='questions_id_0='.$questions_id[0].'&questions_id_1='.$questions_id[1].'&questions_id_2='.$questions_id[2];
$questions_file_url='questions_file_0='.$questions_file[0].'&questions_file_1='.$questions_file[1].'&questions_file_2='.$questions_file[2];
$url = $server.'/startCall.php?call_id='.$call_id.'&phone='.$phone.'&'.$questions_id_url.'&'.$questions_file_url.'&student_id='.$student_id.'&story='
.$story.'&story_id='.$story_id.'&call_number='.$call_number.'&question_number=0&count_english=0&count_hindi=0&insert_receivecall=0';
echo "here"."-----".$url;
$client->account->calls->create(
"+17864310795",
$to,
$url,
array(
'Method' => "GET",
'FallbackMethod' => "GET",
'StatusCallbackMethod' => "GET",
'Record' => "false",
));
} catch (Exception $e) {
// log error
}
}
}
?>
<Response>
<Reject reason="busy"/>
</Response>
I have tried everything, and was hoping I could spot the error
Twilio developer evangelist here.
I think your problem is that you're pushing out more than just XML within that script. You start by setting the content type to XML and echoing the XML declaration, but after that you start to echo what looks like debugging commands, which aren't valid XML, so the parser throws an error.
So, to start, I would comment out or remove anything that echos non XML content from your script.
Let me know if that helps.
hello i need somehow to get top Regional interest and interest over time from
http://www.google.com/trends?q=lingerie+&ctab=0&geo=id&date=all&sort=0
or better
http://www.google.com/insights/search/#q=lingerie&geo=ID&cmpt=q
so i found out that we have to login to export data can anybody give me an example doing this with our google username and password? maybe using curl to export the data? or something else
Thanks for looking in
Adam Ramadhan
Just to be quick about it, I used my xhttp class which is a curl wrapper, and I think the code is easy enough to follow.
<?php
header('content-type: text/plain');
// Set account login info
$data['post'] = array(
'accountType' => 'HOSTED_OR_GOOGLE', // indicates a Google account
'Email' => '', // full email address
'Passwd' => '',
'service' => 'trendspro', // Name of the Google service
'source' => 'codecri.me-example-1.0' // Application's name, e.g. companyName-applicationName-versionID
);
$response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
// Test if unsuccessful
if(!$response['successful']) {
echo 'response: '; print_r($response);
die();
}
// Extract SID
preg_match('/SID=(.+)/', $response['body'], $matches);
$sid = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the SID in cookies
$data['cookies'] = array(
'SID' => $sid
);
$response = xhttp::fetch('http://www.google.com/insights/search/overviewReport?q=lingerie&geo=ID&cmpt=q&content=1&export=1', $data);
// CSV data in the response body
echo $response['body'];
?>
The result is at: http://codecri.me/apps/test/test.google.trends.php
But I'm not sure if the result is what you are looking for.
Since April 2012 Google changed it's auth policy, edit the Arvin's code as follows:
// Extract Auth
preg_match('/Auth=(.+)/', $response['body'], $matches);
$auth = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the Authorization header
$data['headers'] = array(
'Authorization' => 'GoogleLogin auth='.$auth
);
The curl man page describes how to provide username and password. Have you tried the -u flag?
-u/--user
Specify the user name and password to use for server authentication. Overrides -n/--netrc and --netrc-optional.
If you just give the user name (without entering a colon) curl will prompt for a password.
If you use an SSPI-enabled curl binary and do NTLM authentication, you can force curl to pick up the user name and password from your environment by simply specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.