I have a question about the use off the http api from the company clickatell.
They actually have several api that you can use, amongst are xml and smtp also.
Does anyone have any experience with those, especially with the http api.
For the http api:
Does this php code actually doing the work in the background?
This line $ret = file($url); -
I am sorry, I haven't setup anything yet to test it. I am just trying to find out wich api I can start testing with -.
Also, is there a performance difference between using smtp api and http api?
// SMS gateway script
$user = "XXXX";
$password = "XXXXXX";
$api_id = "XXXXXX";
$baseurl ="http://api.clickatell.com";
$text = urlencode("HTTP://WWW.TIMES.COM/DOWNLOADS/SUGRAFREE.SISX");
$to = $_POST["phone number"];
// auth call
$url = "$baseurl/http/auth?user=$user&password=$password&api_id=$api_id";
// do auth call
$ret = file($url);
// split our response. return string is on first line of the data returned
$sess = split(":",$ret[0]);
if ($sess[0] == "OK") {
$sess_id = trim($sess[1]); // remove any whitespace
$url = "$baseurl/http/sendmsg?session_id=$sess_id&to=$to&text=$text";
// do sendmsg call
$ret = file($url);
$send = split(":",$ret[0]);
if ($send[0] == "ID")
echo "An Email with account details and SMS has been sent..
thanks, Richard
I have experience with clickatell API - a good one.
SMTP is slower - you need your email to get to the clickatell servers. which could take a second or a minute.
HTTP is much better and recommended, moreover you can create one session and send multiple sms in one go.
ps: i have not tested your code, but it should work, although i would recommend checking CURL library for HTTP connections.
Related
Using the Twilio API, I've got my PHP functioning to send to one phone number, and can successfully send. We're looking to send to multiple numbers from one request and to do so, I've set up an array of numbers to iterate through, however, I keep getting a 500 error when I attempt to send the message by hitting the URL. Below is the file I'm working with.
Running PHP 7.2 on a Linux server. I'm running CentOS 7.7 and Apache 2.4.43 if that matters at all.
// Require the bundled autoload file - the path may need to change
// based on where you downloaded and unzipped the SDK
require __DIR__ . '/twilio-php-master/src/Twilio/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'XXXXXXXX';
$token = 'XXXXXXXX';
$client = new Client($sid, $token);
$a = array('+15555555555', '+15555555556');
$bodyTxt = “This is a test of sending the text message to multiple phone numbers.”
// Use the client to do fun stuff like send text messages!
foreach ($a as $v) {
$message = $twilio->messages
$client->messages->create($v, // to
[
"body" => $bodyTxt,
"from" => "+15555555557",
]
);
print($message->sid);
}
);
I'm not super familiar with PHP as I'm mostly in marketing, but I'm deputizing as developer in these crazy times because I know just enough to be dangerous. I'm thinking it is something with the foreach section, as that's the only piece that has changed from the single send.
Any help is appreciated!
Figured it out thanks to the help from #LuisE! I went through and figured out where I was missing the semicolons after the array, the $bodyTxt, and the $message = $twilio->messages.
// Require the bundled autoload file - the path may need to change
// based on where you downloaded and unzipped the SDK
require __DIR__ . '/twilio-php-master/src/Twilio/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'XXXXXXXXXX';
$token = 'XXXXXXXXX';
$client = new Client($sid, $token);
$a = array('+15555555555', '+15555555556');
$bodyTxt = 'This is a test of sending the text message to multiple phone numbers.';
// Use the client to do fun stuff like send text messages!
foreach ($a as $v) {
$message = $twilio->messages;
$client->messages->create($v, // to
[
"body" => $bodyTxt,
"from" => "+15555555557",
]
);
print($message->sid);
}
I'm creating an AI Assistant using Dialogflow and I need to use Google APIs (google calendar and gmail). The APIs were working perfectly (I used this as reference). However, when I integrated my code with the dialogflow webhook, it returns Webhook Call failed. Error: 500 Internal Server Error.
here is a code snippet:
$client = new Google_Client();
$client->addScope(Google_Service_Gmail::GMAIL_READONLY); //view your emails and settings
$client->addScope(Google_Service_Gmail::GMAIL_COMPOSE); //manage drafts and send emails
$client->addScope(Google_Service_Gmail::GMAIL_MODIFY);
$client->addScope(Google_Service_Gmail::GMAIL_SEND); //send email on your behalf
$client->addScope(Google_Service_Calendar::CALENDAR); //manage calendar
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('auto');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_SESSION['access_token']) && $_SESSION['access_token']){
$client->setAccessToken($_SESSION['access_token']);
$gmail = new Google_Service_Gmail($client);
$user = "emailaddress#gmail.com";
$calendar = new Google_Service_Calendar($client);
$intent = $json->queryResult->intent->displayName;
$location_any = $json->queryResult->parameters->location_any;
$text = $json->queryResult->parameters->text;
$name = $json->queryResult->parameters->name;
$choice = $json->queryResult->parameters->choice;
$subject = $json->queryResult->parameters->subject;
$location = $json->queryResult->parameters->location;
$description = $json->queryResult->parameters->description;
$startDateTime = $json->queryResult->parameters->startDateTime;
$endDateTime = $json->queryResult->parameters->endDateTime;
if($intent== "UnreadMessages"){
$unread = unReadMessages($gmail, $user);
$speech = "You have ".$unread." messages";
}
else if($intent == "GetSchedule"){
$events = get_event($calendar);
if($events){
$reply = "You have the following events coming up:";
foreach($events as $event){
$eventName = $event['eventName'];
$eventTime = $event['time'];
$reply .= $eventName."is at".$eventTime;
}
$speech = $reply;
}
else{
$speech = "You don't have any events coming up.";
}
}
}
I'm suspecting it may be because of the authentication process that's required everytime I try to run the app, since the error only starts popping up whenever I check for session tokens. My problem now is how do I remove this authentication process?
You have several serious issues with your approach here, but most of them result from you treating the interaction with the Google Assistant like it was a browser hitting your web page. Although Actions on Google uses HTTPS and a webhook, it is otherwise not really like a browser at all.
For example, you check $_SESSION to see if an access token has already been set. $_SESSION is typically implemented by setting a session ID in the browser with a session cookie. The Assistant doesn't use cookies at all. Although it has a userStorage object which can be used it similar ways, this is accessed very differently.
It isn't clear if this is what is causing the error, or if the problem is related here somewhere. If you do have error logs, this would be useful to include in the question.
There is a lot that remains unclear. Primarily - where does the auth token come from in the first place in your code.
In a purely web-based OAuth scheme, you'll direct the user to log in using Google Sign In and, as part of that process, request authorization to access their Drive and GMail. Google Sign In for the Assistant doesn't allow you to do that - all it gives you is an Identity Token.
You can use Account Linking to link the Assistant account to your system - but this requires you to have an OAuth server that generates the auth token that the Assistant will give back to you. This is your OAuth token - not one that comes from Google (unless you're proxying it).
If you have a web-based way to get authorization, you can leverage this to provide access through the Assistant as well using Google Sign In for the Assistant.
I'm using sendgrid/sendgrid-php the repo on github to send transnational emails. Today I've updated the library, the new one uses the API v3 whereas I used v2 before. I've changed the code as per their examples, here is a dump of my SendGrid\Mail object:
The problem is that I'm constantly receiving the 400 BAD REQUEST error without any additional info:
What am I doing wrong? The mail object seems to be correct.
I'm trying to send the email the following way:
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
$request_body = [creating the mail object];
$response = $sg->client->mail()->send()->post($request_body);
I was having the same issue and discovered all personalizations need to be strings with double quotes. In your example:
$md_email_id = (string)26921
More info https://github.com/sendgrid/sendgrid-php/issues/264
I saw a couple of days ago this tutorial on youtube.
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that $update = file_get_contents('php://input'); is the right way, to be used before $update = file_get_contents($website."/getupdates");. My question how can I use php://input to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com".
If you use selfsigned ssl you have to point to the ssl path ,,
use the ssh to run this command after filling it with your real data ,,
curl -F "url=https://example.com/myscript.php" -F "certificate=#/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
After change to WebHook method, you need to put as follows, since now we are going to handle one message at time. For me works perfectly.
instead
$chatId = $updateArray["result"][0]["message"]["chat"]["id"];
to
$chatID = $update["message"]["chat"]["id"];
this is the answer for all of your problems.
follow this step after you got a secret token for your bot:
create file in your website https://yourdomain.com/secret-folder/index.php
create your php file like this :
<?php
$website = 'https://api.telegram.org/bot123456789:1234567890ABCDEF1234567890ABCDEF123/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])){
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
if ( $text == '/start' ) {
// send welcome message
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Welcome to my bot");
}else{
// send another message or do your logic (up to you)
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=some text here");
}
}
?>
Set Your Webhook from this bot #set_webhookbot
choose command or type ' ست وب هوک '
reply with your secret bot token ex: ' 123456789:1234567890ABCDEF1234567890ABCDEF123 '
reply with your webhook address 'https://yourdomain.com/secret-folder/index.php'
reply with /setwebhook
if you follow step by step its will work.
enjoy it !!
Sorry for digging up this old question so enthusiastically, I had exactly the same question as you.
I think actually the answer may be easier yet less satisfying as we hoped: I don't think it's possible to get a list of previous messages to the bot while using the webhook.
Namely: what this does, is run the PHP script directly as soon as the bot receives a message. Nothing is stored in an accessible database, hence no updateArray is returned.
I came across this example, which shows how php://input works. I guess the solution to display a list of messages would be, let the php script store the message in a database everytime a message is 'forwarded' via the webhook.
If anyone found something else: I'm very interested.
As per my understanding from your code snippet above, you need to use php://input within double quotes instead of single quotes. In php, we are having bing difference in this use case.
I'm using Excel VBA to get a user's oAuth2 token for the mail.google.com scope for a native application. It works fine so I have the the user's Access Token (it refreshes if it expires) and I have the user's email address. I was using Zend SMTP to send the emails but found out there are limits to bulk sending emails this way (currently my account is locked out due to going over quota while trying to figure this out over the weekend). My client may send 2,000 emails at once and locking themselves out of their Gmail account for 24 hours is unacceptable. I think using the Gmail REST API will work, as it has higher quotas, but not finding any detailed PHP examples of how to create and send an HTML email via an HTTP request.
I know I have to create the MIME email and think I can figure that out (using this thread stackoverflow.com/questions/24940984/send-email-using-gmail-api-and-google-api-php-client) or from the Zend emails I was successfully creating. My question is what PHP code do I use to create and send the email?
The Google Dev examples all reference /userId/ (from developers.google.com/gmail/api/v1/reference/) but not sure where to get that if I just have the users token and their email address.
I assume it's something like this:
<?php
require 'GoogleAPI/src/Google/autoload.php';
extract($_POST); // use to get my client token, client's email address, the email to, cc, bcc, subject, body, etc.
//<Build the email $mime message here>
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service->users_messages->send('me', $m);
?>
I don't know where to put the user's token. I know 'me' is the person that is authenticated.
I'm open to using an HTTP request as well, something like https://mywebsite.com/sendgmail.php?token=[UsersToken]&UserEmail=joe#test.com&ToEmail=toperson#xyz.com&Subject=HI&Body=Thanks for your help instead of the post method.
Just not sure how to implement that either.
I'm self taught PHP and VBA and new to the google api world so please forgive me if this is easy. I'm also looking into boxspring but trying to use the native APIs and PHP first.
EDIT:
So I've tried this using the examples but getting an error that my token is not in proper JSON format. I just want to send the token as a string. If I can't is there a way to make the string into JSON so oauth2 will accept it?:
<?php
require 'GoogleAPI/src/Google/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
$client = new Google_Client();
$client->setAccessToken('ya29.hwFcwk2M73vaPwNObeuwizHGjXT2y6UsAFEcDIvRAoWTM28gu2pJeK4GiMySkfAllTOQvXVMYfffff');
// Get the API client and construct the service object.
//$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
?>
Error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message
'Could not json decode the token' in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php:179
Stack trace: #0
/home/[my domain]/public/GoogleAPI/src/Google/Client.php(215):
Google_Auth_OAuth2->setAccessToken('ya29.hwFcwk2M73...') #1
/home/[my domain]/public/labels.php(17):
Google_Client->setAccessToken('ya29.hwFcwk2M73...') #2 {main} thrown
in
/home/[my domain]/public/GoogleAPI/src/Google/Auth/OAuth2.php
on line 179
I'm sure I'm making this more difficult than it should be. I'm using the PHP example of showing a users labels, even though my final goal is to send emails.