Youtube Data API v3 - problems with quota usage - youtube-api

In my application I want to use quota that is user based (requests/second/user). I'am sending random (for test queries) quotaUser with all of my requests. But, in the console, I see an increase in the overall use of the quota (project console view). The transfer of the quotaUser parameter does not affect anything. Perhaps I did not correctly understand the documentation on the use of quotas. Is it possible to execute more than 1,000,000 requests per day from multiple application users?
Here is my code:
$client = new Google_Client();
$client->setAuthConfigFile(SITE_PATH . '/vendor/access_data.json');
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . '/test', FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$youtube = new Google_Service_YouTube($client);
if (isset($_GET['code']))
{
$userId = rand(1000, 100000);
$client->authenticate($_GET['code']);
$token = $client->getAccessToken();
$client->setAccessToken($token);
$channelsResponse = $youtube->channels->listChannels('snippet,contentDetails,statistics,status,brandingSettings', array(
'mine' => 'true',
'quotaUser' => $userId
));
$videoResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
'playlistId' => $channelsResponse['items'][0]['contentDetails']['relatedPlaylists']['uploads'],
'maxResults'=> '50',
'quotaUser' => $userId
));
$videos = [];
foreach($videoResponse['items'] as $video)
{
$videos[] = $video['snippet']['resourceId']['videoId'];
}
while(isset($videoResponse['nextPageToken']))
{
$videoResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
'playlistId' => $channelsResponse['items'][0]['contentDetails']['relatedPlaylists']['uploads'],
'maxResults'=> '50',
'pageToken' => $videoResponse['nextPageToken']
));
foreach($videoResponse['items'] as $video)
{
$videos[] = $video['snippet']['resourceId']['videoId'];
}
}
print_r($videos);
}

Related

Trying to connect two calls with Twilio using the first call sid to connect to the next call

I am new to Laravel 9 and usage of Twilio API.
I am trying to create a scenario where a customer_care will call the first participant and after talking with the participant it will call the second participant with whom the first participant will communicate. While calling the second participant, the first participant's call will be kept on hold and after the second participant receives the call both their call will be merged so that they are connected to the same call.
I have written two separate function one for the first call and the other for the second call . The first function is:
public function twiliocall1(Request $request) {
$returnArray = array();
$status = "Error";
$msg = "Call not started";
$validator = Validator::make($request->all(), [
'participants' => 'required|array',
'twilloNo' => 'required',
'contact_id' => 'required'
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
}
$twilloNo = $request->input('twilloNo');
$participants = $request->input('participants');
$sid = "xxxxx";
$token = "yyyy";
$client = new Client($sid, $token);
if (!empty($participants)) {
foreach($participants as $participant) {
$call1 = $client->account->calls->create(
$participant,
$twilloNo,
array("url" => "https://lbwr.operative.dev/multitenant/public/files/conference.php")
);
}
$status = "Success";
$msg = "Call started";
echo($call1->sid);
}
$returnArray['status'] = $status;
$returnArray['msg'] = $msg;
return response()->json($returnArray, 200);
}
The second function is:
public function twiliocall2(Request $request) {
$returnArray = array();
$status = "Error";
$msg = "Call not started";
$validator = Validator::make($request->all(), [
'participants' => 'required|array',
'twilloNo' => 'required',
'contact_id' => 'required',
'sid' => 'required'
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
}
$twilloNo = $request->input('twilloNo');
$participants = $request->input('participants');
$parent_sid = $request->input('sid');
$sid = "xxxx";
$token = "yyyy";
$client = new Client($sid, $token);
foreach($participants as $participant) {
$call = $client->account->calls->get($parent_sid);
$call->update(
$participant,
$twilloNo,
array(
"Url" => "http://demo.twilio.com/docs/voice.xml",
"Method" => "POST"));
}
$status = "Success";
$msg = "Call started";
$returnArray['status'] = $status;
$returnArray['msg'] = $msg;
return response()->json($returnArray, 200);
}
$sid and $token value is same for both the function. I am trying to call the first function using the following json array:
{
"participants":["12345"],
"twilloNo":"68564",
"contact_id":"1234"
}
And on hitting I am getting the sid of this call which I am passing as a json array element to the function twiliocall2() as:
{
"participants":["+7777"],
"twilloNo":"111122",
"contact_id":"1023",
"sid":"fdthgfjkhbklnj"
}
All the values are changed.
The problem arises when I am calling the second function with this Json array as it throws an error:
Twilio\Exceptions\TwilioException: Unknown subresource get in file /opt/lampp/htdocs/multitenant/vendor/twilio/sdk/src/Twilio/Rest/Api/V2010/Account/CallList.php
Kindly suggest if possible where am I going wrong. I am not getting any idea how to implement this scenario any further.

Trying to setup an conference call using Twilio API in laravel 9 but facing issue while creating the conference instance

The code in the Controller is as follows which parse an JSON and creates a Conference object where the error is occouring:
public function twilioConferenceCall(Request $request) {
$returnArray = array();
$status = "Error";
$msg = "Call not started";
$validator = Validator::make($request->all(), [
'participants' => 'required|array',
'fromNo' => 'required|numeric',
'twilloNo' => 'required',
'contact_id' => 'required'
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
}
$fromNo = $request->input('fromNo');
$twilloNo = $request->input('twilloNo');
$sid = "someid";
$token = "sometoken";
$client = new Client($sid, $token);
$conference = $client->conferences->create([
'friendlyName' => 'Test Conference Call'
]);
$conference_sid = $conference->sid;
if ($fromNo != "" && !empty($request->participants)) {
foreach($request->participants as $participant) {
$concall = $client->account->calls->create(
$participant,
$twilloNo,
array(
"url" => "http://twimlets.com/conference?Name=Test%20Conference%20Call&ConferenceSid=".$conference_sid."&Moderators%5B0%5D=".$fromNo
)
);
$status = "Success";
$msg = "Started call to " . $participant;
}
}
$returnArray['status'] = $status;
$returnArray['msg'] = $msg;
return response()->json($returnArray, 200);
}
The JSON which am I sending is as follows:
{
"participants":["+1234","+9999"],
"fromNo":"+5678",
"twilloNo":"119988",
"contact_id":"1057"
}
The error which it throws is:
Error: Call to undefined method Twilio\Rest\Api\V2010\Account\ConferenceList::create()
I have included the following headers in my file
use Twilio\autoload;
use Twilio\Rest\Client;
Kindly suggest where am I doing wrong.

Microsoft Graph - Get Token from Authorisation Response

I am following the instructions here:
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0#3-get-a-token
I get the authorisation response and therefore the required code, but when I request the token I get a "HTTP/1.1 401 Unauthorized" response.
This is my code (not for production, just for me to get the flow/code right first):
<?php
/*
Auth
https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0
*/
define("HOST", 'https://login.microsoftonline.com');
define("TENANT", 'common');
define("AUTH_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/authorize');
define("TOKEN_ENDPOINT", HOST.'/'.TENANT.'/oauth2/v2.0/token');
define("CLIENT_ID", '<< FROM AZURE PORTAL >>');
define("CLIENT_SECRET", '<< FROM AZURE PORTAL >>');
define("ALL_SCOPES", rawurlencode('offline_access user.read mail.read'));
define("CALLBACK", rawurlencode('http://localhost:300/graph2/auth.php'));
// Build URL
$url = AUTH_ENDPOINT."?client_id=".CLIENT_ID;
$url .= "&response_type=code";
$url .= "&redirect_uri=".CALLBACK;
$url .= "&response_mode=query";
$url .= "&scope=".ALL_SCOPES;
echo "<a href=$url>$url</a>";
if (isset($_GET))
{
echo '<pre>';print_r($_GET);echo'</pre>';
if (isset($_GET['code']))
{
// Got authorisation code - now need token
$response = requestAccessTokenByVerifier($_GET['code']);
echo ">".$response;
}
}
function requestAccessTokenByVerifier($verifier)
{
return requestAccessToken(
array(
'client_id' => CLIENT_ID,
'redirect_uri' => CALLBACK,
'client_secret' => CLIENT_SECRET,
'code' => $verifier,
'grant_type' => 'authorization_code',
'scope' => ALL_SCOPES
)
);
}
function requestAccessToken($content)
{
$response = sendRequest(TOKEN_ENDPOINT, 'POST', $content);
if ($response !== false)
{
$authToken = json_decode($response);
if (!empty($authToken) && !empty($authToken->{ACCESSTOKEN})) return $authToken;
}
die("No access token");
return false;
}
function sendRequest($url, $method = 'GET', $data = array(), $headers = array('Content-Type: application/x-www-form-urlencoded'))
{
$context = stream_context_create(
array(
'http' => array(
'method' => $method,
'header' => $headers,
'content' => buildQueryString($data)
)
)
);
echo "URL: $url<br>";
echo '<pre>';print_r($data);echo '</pre>';
echo buildQueryString($data)."<br>";
$response = file_get_contents($url, false, $context);
echo '<pre>';var_dump($http_response_header);echo '</pre>';
return $response;
}
function buildQueryString($array)
{
$result = '';
foreach ($array as $k => $v)
{
if ($result == '') $prefix = ''; else $prefix = '&';
$result .= $prefix . $k . '=' . $v;
}
return $result;
}
?>
As you will see I've put a few basic diagnostics in there which show I am getting the code required successfully, but then not being able to get a token from the code.
Can anybody suggest what to try next, I wonder either from a debugging point of view or alternative approaches.
Thanks.
OK, after digging around I realised I'd made a stupid mistake, but just in case anybody else does the same - you need to use the client secret value not id!
I've deleted that client secret :)
Hope that helps somebody else bashing their head against a brick wall.

Post Multiple images by statuses/update_with_media twitter api of abraham's twitteroauth library

I am trying to post multiple images by statuses/update_with_media twitter api of abraham's twitteroauth library.
I am posting single image but not multiple images.
My code is like below:
$params = array('media[]' => file_get_contents($image_url),
'status' => $message
);
$connection->post('statuses/update_with_media',$params,true);
Where $connection is a object of TwitterOAuth.
Function of TwitterOAuth library is below:
function post($url, $parameters = array(), $multipart = false) {
$response = $this->oAuthRequest($url, 'POST', $parameters, $multipart);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
I know I have to do some change in media[].But I can not get proper output.
So please suggest me.
Thanks in advance
Harry Shah
You can post multiple images on twitter like this
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token,
$access_token_secret);
$firstimage = $connection->upload('media/upload', ['media' => '/path/to/file/kabootar1.jpg']);
$secondimage = $connection->upload('media/upload', ['media' => '/path/to/file/kabootar2.jpg']);
$parameters = [
'status' => 'This is a test tweet',
'media_ids' => implode(',', [$firstimage->media_id_string, $secondimage->media_id_string])];
$output = $connection->post('statuses/update', $parameters);

Twitter says "Could not authenticate you" when space inside a parameter

The code below works perfectly fine if, $searchterm = "Chinmay", but doesn't work correct, when the $searchterm has a space in it. I have tried many encoding and have no luck with it.
Section 1 - Getting the URL and Parameters
$searchterm = "Chinmay+Patel";
$params = array( "q" => $searchterm );
$url = 'https://api.twitter.com/1.1/users/search.json';
Section 2 - Building the Signature
$oauth = array(
'oauth_consumer_key' => \Config::get("oauth-4-laravel::consumers.Twitter.client_id"),
'oauth_nonce' => hash('SHA1', time()),
'oauth_signature' => '',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $this->twitter_user->access_token,
'oauth_version' => '1.0'
);
foreach ($oauth as $key => $value)
{
if (empty($value)) continue;
$oauth_vals[] = "{$key}={$value}";
}
if( !empty( $params ) ){
foreach ($params as $key => $value) {
if(empty($value)) continue;
$oauth_vals[] = "{$key}={$value}";
}
}
$base = 'GET&' . rawurlencode($url) . '&' . rawurlencode(implode('&', $oauth_vals) );// . '&'. implode( '&', $params);
$composite_key = rawurlencode(\Config::get("oauth-4-laravel::consumers.Twitter.client_secret")) . '&' . rawurlencode($this->twitter_user->secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base, $composite_key, true));
$oauth['oauth_signature'] = rawurlencode($oauth_signature);
Section 3 - Building the request header
foreach ($oauth as $key => $value)
{
$auth_header[] = "{$key}=\"{$value}\"";
}
$auth_header = implode(', ', $auth_header);
Section 4 - Building the url and making the request
if( !empty( $params ) ){
$url .= "?" . http_build_query( $params );
}
$verbose = fopen('php://temp', 'rw+');
$options = array(
CURLOPT_HTTPHEADER => array("Authorization: OAuth {$auth_header}"),
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPGET => true,
// DEBUGGING
CURLOPT_VERBOSE => TRUE,
CURLOPT_STDERR => $verbose
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json, true);
rewind($verbose);
Section 5 - Outputting the data
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
var_dump( $twitter_data );
What could be the issue? A little bit out of scope for the question, but this code doesn't work with multiple parameters either. For example, if I add the count parameter, it gives me the same error.

Resources