Twilio API PHP Page Records can not be deserialized - twilio

Im trying to get a list of phone numbers under my Twilio account. Im using their example below, I took out the sid and token for security reasons.
include('/lib/Vendor/autoload.php');
use Twilio\Rest\Client;
$sid = "";
$token = "";
$client = new Client($sid,$token);
foreach ($client->incomingPhoneNumbers->read() as $number) {
echo $number->phoneNumber;
}
However I get this error:
Fatal error: Uncaught exception
'Twilio\Exceptions\DeserializeException' with message 'Page Records
can not be deserialized' in
E:\websites\twiliosite\lib\Vendor\twilio\sdk\Twilio\Page.php:90
Any idea what Im doing wrong? I googled this and couldnt find anything.

Twilio developer evangelist here.
Looks like that is thrown here: https://github.com/twilio/twilio-php/blob/master/Twilio/Page.php#L90
I've only taken a glance at the code, but it looks to me like if a response body doesn't contain the page of data that was expected and isn't empty then it throws that error.
This could perhaps happen if the connection was interrupted and the page of data was delivered incomplete. That might explain why it worked for you on the second attempt.

Related

Discord Oauth2 receiving 'invalid client' error

I had Discord Oauth2 implemented so that my users could log into my website by authenticating through Discord. For months, everything worked great and now all of the sudden it stopped working.
Per Discord's oauth2 instructions,https://discordapp.com/developers/docs/topics/oauth2#shared-resources, I am able to successfully acquire the access code that is meant to be traded for the access token. However, when I try to receive the access token I receive an 'invalid_client' error.
First, I am hitting this endpoint:
https://discordapp.com/api/oauth2/authorize?client_id=${process.env.CLIENT_ID}&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Flogin%2Fdiscord%2Fcallback&response_type=code&scope=identify%20email%20gdm.join
which successfully returns the following:
http://localhost:5000/login/discord/callback?code={some_access_code}
The access code is then sent back to discord to obtain the access token. Here is the code that is failing:
export function getDiscordAccessToken(accessCode, call) {
const redirect = call === 'login' ? process.env.DISCORD_LOGIN_REDIRECT : process.env.DISCORD_CONNECT_REDIRECT
return new Promise((resolve, reject) => {
axios
.post(
`https://discordapp.com/api/oauth2/token?client_id=${process.env.DISCORD_CLIENTID}&client_secret=${process.env.DISCORD_SECRET}&grant_type=authorization_code&code=${accessCode}&redirect_uri=${redirect}&scope=identify%20email%20gdm.join`
)
.then(res => {
resolve(res.data)
})
.catch(err => {
// log error to db
console.log("Here is your error: ", err.response)
reject(err.response)
})
})
}
This code was working for months with no problems. Then, all of the sudden it stopped working. I even checked the Discord change logs which can be found here, https://discordapp.com/developers/docs/change-log, but I found no reference to authentication changes.
Any help you can provide is greatly appreciated!
The query parameters should be in the BODY of the POST request, not the URL for the oauth/token url.
Discord recently pushed a update to the oAuth2 which makes it confine more with the standard. This means they no longer support parameters in the URL for POST, but instead require them to be in the body and form encoded (basically the same, but in the body and without the leading ?).
So you basically need (not tested):
axios.post(
`https://discordapp.com/api/oauth2/token`,
`client_id=${process.env.DISCORD_CLIENTID}&client_secret=${process.env.DISCORD_SECRET}&grant_type=client_credentials&code=${accessCode}&redirect_uri=${redirect}&scope=identify%20email%20gdm.join`
)
I know the question has already been answered, but in my case I copied a wrong secret key. Just make sure that you copy the right one.
Secret Key is located under OAuth2 Tab and not under General Information tab on discord developer's dashboard.

twilio The requested resource was not found

I tried to get a list of all conferences via Twilio PHP helper library, but get 404 error. My code:
$client = new Client($accountSid, $authToken);
foreach ($client->conferences->read() as $conference) {
var_dump($conference);
}
Error:
[HTTP 404] Unable to fetch page: The requested resource /2010-04-01/Accounts/twilio.account_sid/Conferences.json was not found
Thanks for the help in advance!
The problem was in bad credentials I setted. I used test credentials that are only for REST API testing purposes. When I setted correct credentials from https://www.twilio.com/console the problem was solved. Thanks Shachaf.Gortler for the some help.

Refresh token must be passed in or set as part of setAccessToken Youtube API

I have the following code
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$newAccessToken = $client->getAccessToken();
$accessToken = array_merge($accessToken, $newAccessToken);
file_put_contents($credentialsPath, json_encode($accessToken));
}
}
But after an hour, if I try to use Youtube Data API, I am getting the following error,
Fatal error: Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php:267 Stack trace: #0 /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/youtube.php(26): Google_Client->fetchAccessTokenWithRefreshToken(NULL) #1 /var/sentora/hostdata/zadmin/public_html/channel/apiwrap.php(3): require_once('/var/sentora/ho...') #2 {main} thrown in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php on line 267
Please help.
You need to set these 2 things. The refresh token is not returned because we didn't force the approvalPrompt. The offline mode is not enough. We must force the approvalPrompt. Also, the redirect URI must be set before these two options. It worked for me.
$client = new Google_Client();
$client->setApplicationName('Project Name');
$client->setScopes('SCOPES');
$client->setAuthConfig('JSON_FILE_PATH');
$client->setRedirectUri($this->redirectUri);
$client->setAccessType('offline'); //this line is magic point
$client->setApprovalPrompt('force'); //this line is magic point
This is worked for me. i am able to get new token using refresh token.

Twilio Response Class not found

I am new to Twilio. To learn the basics, I followed the instructions here:
https://www.twilio.com/docs/howto/walkthrough/click-to-call/php/laravel#12
At first, my phone would ring, and I would receive a generic message. Impressed, I upgraded my account. Now I receive a call where a voice says "We're sorry an application error has occurred."
I checked my Alerts in Twilio, and found Error: 12100 - Document parse failure
So I checked the url of my outbound.php and realized that there is a PHP error here. The error is
Fatal error: Class 'Response' not found in
/home/......./outbound.php on line 16
After some searching, I can't find anyone else discussing this same problem. Finally, the worst part, I can't even find any reference to a Response class in the Twilio Helper Library.
Here is my entire code block for the page in question.
<?php
error_reporting(E_ALL);
require_once 'twilio-library/Services/Twilio.php';
// A message for Twilio's TTS engine to repeat
$sayMessage = 'Thanks for contacting our sales department. If this were a
real click to call application, we would redirect your call to our
sales team right now using the Dial tag.';
$twiml = new Services_Twilio_Twiml();
$twiml->say($sayMessage, array('voice' => 'alice'));
// $response->dial('+12345675309');
$response = Response::make($twiml, 200);
$response->header('Content-Type', 'text/xml');
return $response;
?>
If I change this file to static, well formatted XML then the error stops.
Twilio developer evangelist here.
The tutorial you were following was based within the Laravel framework, which is where the Response class was expecting to come from.
If you are using the PHP TwiML builder in just a plain PHP file, you should be able to just print the $twiml. I'd probably add a Content-Type of text/xml as well, just to be safe. Like this:
<?php
error_reporting(E_ALL);
require_once 'twilio-library/Services/Twilio.php';
// A message for Twilio's TTS engine to repeat
$sayMessage = 'Thanks for contacting our sales department. If this were a
real click to call application, we would redirect your call to our
sales team right now using the Dial tag.';
$twiml = new Services_Twilio_Twiml();
$twiml->say($sayMessage, array('voice' => 'alice'));
// $twiml->dial('+12345675309');
header('Content-type: application/xml');
print $twiml;
?>
Let me know if this helps at all!

Google YouTube API v3 :: Server-to-Server Upload Service

Our project lets users upload videos to OUR public youtube channel when they are signed into our session. We do not want to require additional OAuth2 verification, and instead follow the follow of Google API v2.
My code (php) and error are below, but my general question is: can my server make the insert-video POST using my API key/secrets without requiring the user to authenticate.
This question - Google Calendar API v3 hardcoded credentials - is very similar. Howevr if CURLing Google for the access_token is the only answer, i'll be disappointed. Thanks regardless.
Google API V3 Settings:
Client ID: xxxx.apps.googleusercontent.com
Email address: xxxx#developer.gserviceaccount.com
Client secret: xxxx
Redirect URIs: http://fbtabs.imagendigital.co/unilever/sedal/surprise/galeria
JavaScript origins: https://fbtabs.imagendigital.co
API key:
AIzaSyBgS-jMJQUPIiAyX20xC-encFWTPsR7qxQ
Referers:
Any referer allowed
Activated on: Jul 4, 2013 1:21 PM
Activated by: xxxx#gmail.com – you
Code:
<?php
require_once BASE_CD . 'app/src/Idframework/Tools.php';
require_once BASE_CD . 'app/vendor/google-api-php-client/src/Google_Client.php';
require_once BASE_CD . 'app/vendor/google-api-php-client/src/contrib/Google_YouTubeService.php';
$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxxx');
$client->setRedirectUri('http://fbtabs.imagendigital.co/unilever/sedal/surprise/galeria');
$client->setDeveloperKey('xxxx');
$youtube = new Google_YoutubeService($client);
$snippet = new Google_VideoSnippet();
$status = new Google_VideoStatus();
$video = new Google_Video();
if (isset($_POST['tip_desc'])) $snippet->setDescription($_POST['tip_desc']);
$snippet->setTitle($_POST['tip_name']);
$snippet->setTags(array("sedal","hair","pello","cabello"));
$status->privacyStatus = "public";
$video->setSnippet($snippet);
$video->setStatus($status);
$filename = $_FILES['videoInp']['tmp_name'];
$mime = \Idframework\Tools::get_mime($filename);
try {
$part = "status";
$obj = $youtube->videos->insert($part, $video,
array("data"=>file_get_contents($filename),
"mimeType" => $mime));
} catch(Google_ServiceException $e) {
print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>";
print "Stack trace is ".$e->getTraceAsString();
}
Error:
Notice: Undefined index: content-type in C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\service\Google_MediaFileUpload.php on line 99
Caught Google service Exception 401 message is Error calling POST https://www.googleapis.com/upload/youtube/v3/videos?part=player&uploadType=multipart&key=AIzaSyBgS-jMJQUPIiAyX20xC-encFWTPsR7qxQ: (401) Login Required
Stack trace is #0 C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\io\Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\service\Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 C:\DATA\IDInteractive\SedalSurprise\app\vendor\google-api-php-client\src\contrib\Google_YouTubeService.php(789): Google_ServiceResource->__call('insert', Array) #3 C:\DATA\IDInteractive\SedalSurprise\youtuber.php(56): Google_VideosServiceResource->insert('player', Object(Google_Video), Array) #4 {main}
First off, letting arbitrary users upload videos into a "master" YouTube channel is not recommended, for the reasons outlined in this blog post.
That being said, if you're determined to do it, then you need to include an access token associated with your channel in each upload request. The appropriate way to get a fresh access token (they expire after an hour) is to take a refresh token that you've previously generated and stored somewhere and make an HTTP request to the appropriate URL to get back an access token, as explained in the OAuth 2 documentation. There's no way around that—I'm not sure whether there's a native method in the Google APIs PHP client library that will automate the process for you, but that's what needs to happen under the hood.
The information in Google Calendar API v3 hardcoded credentials does seem relevant.

Resources