Twilio SMS Using PHP (Not Sending or Loading PHP page) - php

So this is what's on the top of the PHP file:
<?php
// Start the session
session_start();
?>
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXX";
$token = "XXXXXXXXXXXXXXXXXX";
$client = new Services_Twilio($sid, $token);
$client->account->messages->sendMessage("+1234567890", "+0987654321", "Please?! I love you <3, Twilio Test");
?>
<?php
// Start the session
session_destroy();
?>
Then I have the <html> beneath.
The Issue I'm having is that the page just loads a white blank page and when I check the Twilio Log to see if any SMS are logged.
But the page loads just fine without the middle PHP (the part that's supposed to send the SMS through Twilio)
The Log is completely empty and shows no record of any outgoing SMS.
Any help would be appreciated!

Where are you getting sendMessage from? According to Docs this is how it is done
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "AC8ed2351ef2156d21a66faf913443188c";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
$sms = $client->account->sms_messages->create("+14158141829", "+14159352345", "Jenny please?! I love you <3", array());
echo $sms->sid;

Related

Refresh token on Google OAuth2 PHP library

I implemented Google OAuth2 for user login on my website.
It works but after 1 hour token expires and login fails.
I read on the web that I need to get the Refresh Token (for Facebook Login I used a Long Lived Token), but code I tried doesn't work.
Here the code:
//LOGIN CALLBACK FROM GOOGLE
$gClient = new Google_Client();
$gClient->setApplicationName(SITE_TITLE);
$gClient->setClientId(get_option('google_api_id')->value);
$gClient->setClientSecret(get_option('google_api_secret')->value);
$gClient->addScope('profile');
$gClient->addScope('email');
$gClient->setRedirectUri(SITE_URL."/login/google/google-callback.php");
if(isset($_GET['code'])) {
$gClient->setAccessType('offline');
$token = $gClient->fetchAccessTokenWithAuthCode($_GET['code']);
$gClient->setAccessToken($token['access_token']);
$_SESSION['google_access_token'] = $token['access_token'];
}
if($gClient->getAccessToken()) {
// Get user profile data from google
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$gpUserProfile = $google_oauthV2->userinfo->get();
}
...
This first snippet works fine.
In this second snipped, when user change page, I verify if login is still active:
$gClient = new Google_Client();
$gClient->setApplicationName(SITE_TITLE);
$gClient->setClientId(get_option('google_api_id')->value);
$gClient->setClientSecret(get_option('google_api_secret')->value);
$gClient->addScope('profile');
$gClient->addScope('email');
$gClient->setAccessType('offline');
$gClient->setAccessToken($_SESSION['google_access_token']);
if($gClient->getAccessToken()) {
if ($gClient->isAccessTokenExpired()) {
$gClient->fetchAccessTokenWithRefreshToken($gClient->getRefreshToken());
}
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$gpUserProfile = $google_oauthV2->userinfo->get();
...
}
This second snipped doesn't work, because method fetchAccessTokenWithRefreshToken($gClient->getRefreshToken()) fails because $gClient->getRefreshToken() is NULL.
I debugged the callback and I saw that $token = $gClient->fetchAccessTokenWithAuthCode returns an array without "refresh_token" field.
Can anyone help me?
Thanks
Bye

Saving Google API Client in PHP

Apologies if I am missing something obvious in this question...
I have an index.php file where I initialise a Google Client, set the scopes, create a service and start pulling data from the Google Tenancy. This works fine.
<?php
require_once 'vendor/autoload.php';
const CLIENT_ID = MY CLIENT ID;
const CLIENT_SECRET = MY SECRET;
const REDIRECT_URI = REDIRECT URI;
session_start();
$client = new Google_Client();
$client->setApplicationName("My Application");
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes('admin scopes');
$adminservice = new Google_Service_Directory($client);
My issue is, I want to get a user's ID from the AdminDirectory API and then pass it to a new page, user.php, with the GET tag id.
So, for example:
<?php
$id = $adminservice->users->get(EMAIL)->id;
?>
<a href = 'user.php?id=<?php echo $id; ?>'>Click Here</a>
How do I transfer my $client variable over to this new user.php page?
I have tried putting the client in $_SESSION['client'] and then extracting it on the new page. I have also tried reinitialising the entire client. Neither seem to work.
Thanks
You have to import the class on the user.php page:
require_once 'vendor/autoload.php';
Next, store the object in the session:
$_SESSION['googleclient'] = $client;
Now to get it on the other page do:
$client = $_SESSION['client'];
If you need anymore help look at this: move object from 1 page to another?

Can I setup a PHP Twilio application server and grant push capabilities

I currently use a Python Twilio application server and grant push capabilities to my tokens with the following lines of code:
#app.route('/accessToken')
def token():
account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
api_key = os.environ.get("API_KEY", API_KEY)
api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET)
push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID", PUSH_CREDENTIAL_SID)
app_sid = os.environ.get("APP_SID", APP_SID)
grant = VoiceGrant(
push_credential_sid=push_credential_sid,
outgoing_application_sid=app_sid
)
token = AccessToken(account_sid, api_key, api_key_secret, IDENTITY)
token.add_grant(grant)
return str(token)
Is there a way for me to do that with PHP? I have loaded Twilio dependencies with composer and can get a token just fine. I just don't know how to add push capabilities to the token. These lines currently generate tokens (but not with push capabilities):
<?php
include('./vendor/autoload.php');
include('./config.php');
include('./randos.php');
use Twilio\Jwt\ClientToken;
use Twilio\Jwt\Grants;
// choose a random username for the connecting user
$identity = $_GET['identity'];
$capability = new ClientToken($TWILIO_ACCOUNT_SID, $TWILIO_AUTH_TOKEN);
$capability->allowClientOutgoing($TWILIO_TWIML_APP_SID);
$capability->allowClientIncoming($identity);
$token = $capability->generateToken();
echo $token;
?>
Thanks to a tip from Zack with Twilio, I finally got this working!
include('./vendor/autoload.php');
include('./config.php');
include('./randos.php');
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants;
use Twilio\Jwt\Grants\VoiceGrant;
use Twilio\Rest\Client;
// choose a random username for the connecting user
$identity = randomUsername();
$token = new AccessToken($TWILIO_ACCOUNT_SID, $API_KEY, $API_KEY_SECRET, 3600, $identity);
$grant = new VoiceGrant();
$grant->setPushCredentialSid($PUSH_CREDENTIAL_SID);
$grant->setOutgoingApplicationSid($TWILIO_TWIML_APP_SID);
$token->addGrant($grant);
echo $token;

How to access the callback status twilio when the call is finished?

I'm trying to access the status AFTER the call is done, and display it in the first page, not in the callback page.
i have calling page:
require 'twilio/Services/Twilio.php';
$sid = "xxx"; // Your Account SID from www.twilio.com/user/account
$token = "xxx"; // Your Auth Token from www.twilio.com/user/account
$client = new Services_Twilio($sid, $token);
try {
$call = $client->account->calls->create(
'000', // From a valid Twilio number
$number, // Call this number
// Read TwiML at this URL when a call connects (hold music)'
"http://myurl.com/voice.xml", array('Method' => 'GET','StatusCallback'=>'http://myurl.com/callback.php'));
if($call->status =='failed')result(array('status'=>'failed status '));
else result(array('status'=>$call->status));
} catch (Exception $e) {
result(array('status'=>'not a valid number'));
}
my issue is that i'm not understanding how i can get the $_POST info that twilio will send to my callback.php on my calling page.php....
Please read Twilio API explaintion Click here for reference from Twilio Site to know the post parameters from Twilio on your callback back page.
http://myurl.com/callback.php
$callDur = $_POST['CallDuration'];
$recdDur = $_POST['RecordingDuration'];
To get these values on other page store them in session and use them where you want.

Writing a twitter API using php that is username specific

I've written a twitter api application using the following tutorial:
http://www.youtube.com/watch?v=GQaPt-gQVRI
How can I modify the script to generate a timeline stream that is specific to a user so that the application when run will show user's timeline stream and not mine (since i wrote the app and therefore it has my twitter credentials)
Thanks
the php application validates my twitter credentials using the following:
<?php
require 'tmhOAuth.php'; // Get it from: https://github.com/themattharris/tmhOAuth
// Use the data from http://dev.twitter.com/apps to fill out this info
// notice the slight name difference in the last two items)
$connection = new tmhOAuth(array(
'consumer_key' => 'my key',
'consumer_secret' => 'my secret',
'user_token' => 'my token', //access token
'user_secret' => 'my user secret' //access token secret
));
// set up parameters to pass
$parameters = array();
if ($_GET['count']) {
$parameters['count'] = strip_tags($_GET['count']);
}
if ($_GET['screen_name']) {
$parameters['screen_name'] = strip_tags($_GET['screen_name']);
}
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else {
$twitter_path = '1.1/statuses/user_timeline.json';
}
$http_code = $connection->request('GET', $connection->url($twitter_path), $parameters );
if ($http_code === 200) { // if everything's good
$response = strip_tags($connection->response['response']);
if ($_GET['callback']) { // if we ask for a jsonp callback function
echo $_GET['callback'],'(', $response,');';
} else {
echo $response;
}
} else {
echo "Error ID: ",$http_code, "<br>\n";
echo "Error: ",$connection->response['error'], "<br>\n";
So without having to pass a new username in the api call, how can i add a snippet to require the user to log in? and if i add that snippet for the user to log in, will the api automatically populate the authentication strings with the user's?
You can send a get request to the following url to get a users timeline.
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2
You can replace the parameters screen_name with the username you want to access, and you can replace count with the number of tweets you would like to get, count is optional and doesn't have to be included.
You can read more about statuses/user_timeline on the office twitter API site: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
If you wish to get a user to sign in then your best bet would be to use the twitteroauth library by abraham
Download and include in your project, then include the library and start a session.
require("twitteroauth/twitteroauth.php");
session_start();
Then create a new instance and authenticate with your app details. You can set a url to redirect to when the user authenticates. You also need to cache your tokens.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET');
$request_token = $twitteroauth->getRequestToken('http://example.com/loggedin.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
Redirect the user to twitter to authenticate
header('Location: '.$twitteroauth->getAuthorizeURL($request_token['oauth_token']));
In the file that you set twitter to redirect to you need to re-authenticate using the tokens created. Twitter will also add a parameter to your url which you use to create a access token for that user. Now when you send GET requests to twitter, it does it on behalf of the user logged in.
require("twitteroauth/twitteroauth.php");
session_start();
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$user_info = $twitteroauth->get('account/verify_credentials');
print_r($user_info);
You can get additional details from $user_info which you can cache or store in a database, which will allow you to remember users that have already authenticated. You will need to use oauth_token and oauth_secret, something like this.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', 'OAUTH_TOKEN', 'OAUTH_SECRET');

Categories