I'm trying to set up my own php accessToken server to grant new token for different user on my ios swift app.
I've set it up already, and can get the token key, however when the videoQuickStart app uses the token key get from my server, it will not connect to room, and even if I try to use the "token.php" from here : https://github.com/TwilioDevEd/video-quickstart-php/blob/master/token.php it still not working.
It seems like my key is not validated?
Can anyone helps?
Here's my implement of server, which is almost identical to the original one.
< ? php
include('/Applications/XAMPP/xamppfiles/htdocs/dashboard/vendor/autoload.php');
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\VideoGrant;
// Required for all Twilio access tokens
$TWILIO_ACCOUNT_SID = 'XXXXX';
$TWILIO_CONFIGURATION_SID = 'XXXX';
$TWILIO_API_KEY = 'XXXX';
$TWILIO_API_SECRET = 'XXXXX';
// An identifier for your app - can be anything you'd like
$identity = $_GET['name'];
// Create access token, which we will serialize and send to the client
$token = new AccessToken(
$TWILIO_ACCOUNT_SID,
$TWILIO_API_KEY,
$TWILIO_API_SECRET,
3600,
$identity
);
$grant = new VideoGrant();
$grant->setConfigurationProfileSid($TWILIO_CONFIGURATION_SID);
$token->addGrant($grant);
// render token to string
echo json_encode(array(
'identity' => $identity,
'token' => $token->toJWT(),
));
?>
It's fixed.
It turns out I misplaced TWILIO_ACCOUNT_SID and TWILIO_CONFIGURATION_SID.
Thanks guys
Related
I am using twitter account activity api's to send/receive messages. In it i am facing problem in generating webhook. First time it was created successfully. In webhook file i am saving messages in database when each time message sent or received. But when I sent message nothing goes in database. Here is webhook file:
const APP_CONSUMER_SECRET = '**********';
// Example token provided by incoming GET request
if(isset($_REQUEST['crc_token'])) {
$token = $_REQUEST['crc_token'];
/**
* Creates a HMAC SHA-256 hash created from the app TOKEN and
* your app Consumer Secret.
* #param token the token provided by the incoming GET request
* #return string
*/
function get_challenge_response($token) {
$hash = hash_hmac('sha256', $token, APP_CONSUMER_SECRET, true);
$response = array(
'response_token' => 'sha256=' . base64_encode($hash)
);
return json_encode($response);
}
}else{
$feedData = file_get_contents('php://input');
$handleData = fopen('twitterDemo.txt', "w" );
fwrite($handleData,$feedData);
fclose($handleData);
$array = json_decode(file_get_contents('php://input'), true);
if (isset($array['direct_message_events'][0]['type']) && $array['direct_message_events'][0]['type'] == 'message_create' ) {
include_once ('config.php');
include_once ('database-queries.php');
$message = $array['direct_message_events'][0]['message_create']['message_data']['text'];
$sender = $array['direct_message_events'][0]['message_create']['sender_id'];
$from = $array['direct_message_events'][0]['message_create']['target']['recipient_id'];
$message_type = 'incoming';
$message_status = 'unread';
$userId = $sender;
$account_name = 'twitter';
$image_url = '';
if(isset($array['direct_message_events'][0]['message_create']['message_data']['attachment'])){
$image_url = "Not Image";
}
$data = array('to'=>$from, 'from'=>$sender, 'msg'=>$message,'image_url' =>$image_url);
insert($data, $account_name, $message_type, $message_status, $conn);
}
}
I thought there might be webhook problem so i deleted the existing app and create new one and set development environment label for it with new name. But for it when i tried to create webhook it gives me error:
[code] => 214 [message] => Webhook URL does not meet the requirements.
Invalid CRC token or json response format.
I dont know whats happening here now. I am using this api to create webhook url
$url = "https://example.com/twitter/webhook.php";
$result = $connection->post("account_activity/all/env_name/webhooks", ["url" => $url]);
Can anyone please help me this out. Any help will be appreciated.
Thanks!
I ran into the same error message.
The problem seem to be that the
if(isset($_REQUEST['crc_token']))
is not working anymore. Though the token is set. I don't know what is causing the problem but when I let the code just fetch the $_REQUEST['crc_token'] and create and print the hash its working.
But I see your code is not calling the get_challenge_response($token) function.
I think
print get_challenge_response($token)
may help? If the Webhook was deactivated by twitter you have to initiate another CRC check:
https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/subscribe-account-activity/guides/securing-webhooks
Your app can also trigger a CRC when needed by making a PUT request with your webhook id. Triggering a CRC is useful as you develop your webhook application, after deploying new code and restarting your service.
I am trying to build a simple MS Graph API call to get familiar with Graph.
However, I can't get it to work. MS Graph keeps giving the error that my token has expired, while it's not.
Code:
<?php
require_once('C:\inetpub\site6\vendor\autoload.php');
// Using newest version of TheNetworg Oauth2
$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
'clientId' => '***************',
'clientSecret' => '**********',
'redirectUri' => 'https://app2.***/test.php'
]);
// Set to use v2 API, skip the line or set the value to Azure::ENDPOINT_VERSION_1_0 if willing to use v1 API
$provider->defaultEndPointVersion = TheNetworg\OAuth2\Client\Provider\Azure::ENDPOINT_VERSION_2_0;
$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);
//echo $baseGraphUri;
$provider->tenant = '*********.onmicrosoft.com'; //Azure AD ID
$provider->authWithResource;
$provider->scope = $baseGraphUri . '/.default';
$token = $provider->getAccessToken('client_credentials', ['scope' => $provider->scope]);
// echo $token;
// Set up our request to the API
$ref= 'users/someuser#mytenant.com';
$response = $provider->get($ref, $token, $headers = []);
// Store the result as an object
$result = json_decode( $response->getBody() );
?>
But I keep getting ended up with error:
PHP Fatal error: Uncaught
League\OAuth2\Client\Provider\Exception\IdentityProviderException:
Your access token has expired. Please renew it before submitting the
request. in
C:\inetpub\site6\vendor\thenetworg\oauth2-azure\src\Provider\Azure.php:394
What am I doing wrong? When I google the error, I get a lot of results telling that I am trying to access MS Graph with an Azure AD Graph token, but when I do echo $baseGraphUri; I really tells me graph.microsoft.com.
I found out what the error is. Although I use "$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);", the library still connects to the Azure AD API instead of the Microsoft Graph API. So it authenticates with the wrong kind (aud) of token.
Adding this line fixed the problem:
$provider->urlAPI = 'https://graph.microsoft.com/';
I was performing Google Sign in on Android Application for the first time. At the client side, I obtained the access token and sent to the PHP server via POST.
By referring to Google's Documentation, the code I used in backend is as follows:
$id_token = $_POST['id_token'];
$CLIENT_ID = "** MY WEB APPLICATION CLIENT ID **";
$client = new Google_Client(['client_id' => $CLIENT_ID]);
$client->setAuthConfigFile('client_secret.json');
...
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$userid = $payload['sub'];
} else {
echo "Invalid Token";
}
When obtaining user id, the error is : "Cannot use object of type Google_Auth_LoginTicket as array"
I am pretty new to Google sign in. Please point out what all has gone wrong.
Found It. I made some modifications to the code
$token_data = $client->verifyIdToken($id_token)->getAttributes();
$user_id = $token_data['payload']['sub'];
Now the user id is retrieved fine.
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;
Im using the following code to read to consumer_key and consumer_secret from config.php, pass it to twitter and retrieve some bits of information back from them.
What the script below attempts to do is 'cache' the request_token and request_secret. So in theory I should be able to reuse those details (all 4 of them to automatically tweet when required).
<?php
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
if (isset($_GET["register"]))
{
// If the "register" parameter is set we create a new TwitterOAuth object
// and request a token
/* Build TwitterOAuth object with client credentials. */
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request = $oauth->getRequestToken();
$request_token = $request["oauth_token"];
$request_token_secret = $request["oauth_token_secret"];
// At this I store the two request tokens somewhere.
file_put_contents("request_token", $request_token);
file_put_contents("request_token_secret", $request_token_secret);
// Generate a request link and output it
$request_link = $oauth->getAuthorizeURL($request);
echo "Request here: " . $request_link . "";
die();
}
elseif (isset($_GET["validate"]))
{
// This is the validation part. I read the stored request
// tokens.
$request_token = file_get_contents("request_token");
$request_token_secret = file_get_contents("request_token_secret");
// Initiate a new TwitterOAuth object. This time we provide them with more details:
// The request token and the request token secret
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);
// Ask Twitter for an access token (and an access token secret)
$request = $oauth->getAccessToken();
// There we go
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
// Now store the two tokens into another file (or database or whatever):
file_put_contents("access_token", $access_token);
file_put_contents("access_token_secret", $access_token_secret);
// Great! Now we've got the access tokens stored.
// Let's verify credentials and output the username.
// Note that this time we're passing TwitterOAuth the access tokens.
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token, $access_token_secret);
// Send an API request to verify credentials
$credentials = $oauth->oAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
// Parse the result (assuming you've got simplexml installed)
$credentials = simplexml_load_string($credentials);
var_dump($credentials);
// And finaly output some text
echo "Access token saved! Authorized as #" . $credentials->screen_name;
die();
}
?>
When i run /?verify&oauth_token=0000000000000000 - It works however trying to resuse the generated tokens etc... I get a 401
Here is the last bit of code where I attempt to reuse the details from Twitter combined with my consumer_key and consumer_secret and get the 401:
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
// Read the access tokens
$access_token = file_get_contents("access_token");
$access_token_secret = file_get_contents("access_token_secret");
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
$access_token, $access_token_secret);
// Post an update to Twitter via your application:
$oauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST');
Not sure whats going wrong, are you able to cache the details or do i need to try something else?
You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.
That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.
twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts)
The image below describes the flow of the OAuth authentication.
Hope it helps.
A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.
require_once 'Zend/Service/Twitter.php';
class Twitter {
protected $_username = '<your_twitter_username>';
protected $_token = '<your_twitter_access_token>';
protected $_secret = '<your_twitter_access_token_secret>';
protected $_twitter = NULL;
//class constructor
public function __construct() {
$this->getTwitter();
}
//singleton twitter object
protected function getTwitter() {
if (null === $this->_twitter) {
$accessToken = new Zend_Oauth_Token_Access;
$accessToken->setToken($this->_token)
->setTokenSecret($this->_secret);
$this->_twitter = new Zend_Service_Twitter(array(
'username' => $this->_username,
'accessToken' => $accessToken,
));
$response = $this->_twitter->account->verifyCredentials();
if ($response->isError()) {
throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
}
}
return $this->_twitter;
}
//send a status message to twitter
public function update( $tweet ) {
$this->getTwitter()->status->update($tweet);
}
}
In your second script, it looks like you aren't setting the Consumer Key and Consumer Secret when you create your TwitterOAuth instance.
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);