Google Youtube data api Caption with transcript - youtube-data-api

Error is return in youtube data api call:https://www.googleapis.com/youtube/v3/captions/id
Other api is working with same code for google youtube api's. Any one with past experience with this issue can share his/her experience. Thanks in advance.
try{
$client = new Google_Client();
$client->setApplicationName('My First Project');
$client_id = get_option('gapi_client_id');
$client_secret = get_option('gapi_client_secret');
$redirect_uri = 'https://income.tube/wp-admin/admin.php?page=rnd-eytes';
$simple_api_key = get_option('rnd-eyts');
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->setScopes([
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtubepartner'
]);
$client->setAccessType('offline');
echo $authCode = get_option('gapi_auth_code');
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAuthConfig($access_token);
// Get the authorized Guzzle HTTP client.
$http = $client->authorize();
$fp = fopen(__DIR__ . '/Libs/YOUR_FILE', 'w');
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$queryParams = [
'tfmt' => 'vtt',
'tlang' => 'fr'
];
$response = $http->request(
'GET',
'/youtube/v3/captions/OdIfTQmbuCS8lIzTWpQoHP66BOQh1VfTCmNAH-qo6vE=',
[
'query' => $queryParams
]
);
echo '<pre>';
print_r($response);
echo '</pre>';
fwrite($fp, $response->getBody()->getContents());
fclose($fp);
}catch(Exception $e){
//catch the exception here
echo '<pre>';
print_r($e);
echo '</pre>';
}

Related

PHP Google Search Console API "invalid_grant" response

I am using following PHP code to fetch data through Google Search Consonle API.
It was working fine 2 months ago but now it's showing invalid grand message instead of data. Please! need your help.
error: '400 - {"error":"invalid_grant","error_description":"Bad Request"}'
I've right credentials included. Also you can see token is saved in file and is being fetched on demand and getting refresh too. I don't why it's stopped working.
Thanks
At the top I've added
use Google_Client;
use Google_Service_Webmasters_SearchAnalyticsQueryRequest;
use Google_Service_Webmasters;
and here is the code
$siteToFetch = (!empty($site)) ? base64_decode($site) : "https://www.siteiamfulluserof.com/";
$client_id = 'XXXXXXXXXXXX-FULL-TOKEN-REMOVED';
$client_secret = 'xxxxxx-xxxxx_xxxxxxxxxxxxxxx-xxxx';
$redirect_uri = 'http://localhost/redirect_url';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAuthConfig(public_path("client_secret_latest.json"));
$client->setScopes("https://www.googleapis.com/auth/webmasters", 'https://www.googleapis.com/auth/webmasters.readonly');
if (file_exists($this->tokenFile)) {
$accessToken = json_decode(file_get_contents($this->tokenFile), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
if (isset($_REQUEST['code'])) {
$authCode = $_REQUEST['code'];
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
if (!file_exists(dirname($this->tokenFile))) {
mkdir(dirname($this->tokenFile), 0700, true);
}
file_put_contents($this->tokenFile, json_encode($accessToken));
} else {
exit('No code found');
}
}
$client->setAccessToken($accessToken);
// Refresh Token if expired.
if ($client->isAccessTokenExpired()) {
$refreshTokenSaved = $client->getRefreshToken();
$client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
}
if ($client->getAccessToken()) {
$googleQuery = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$googleQuery->setStartDate(date('Y-m-d', strtotime('-180 days')));
$googleQuery->setEndDate(date('Y-m-d', strtotime('-3 days')));
$googleQuery->setDimensions(['page', 'date']);
$googleQuery->setSearchType('web');
try {
$service = new Google_Service_Webmasters($client);
$response = $service->searchanalytics->query($sitesFetched[0]["site"], $googleQuery);
$siteData = [];
foreach ($response as $row) {
$siteData[] = [
"site" => $row->keys[0],
"date" => $row->keys[1],
"clicks" => $row->clicks,
"impressions" => $row->impressions,
"ctr" => $row->ctr,
"position" => $row->position,
];
}
} catch (\Exception $e) {
$error = json_decode($e->getMessage());
if ($error->error = "invalid_grant") {
echo "You don't have proper permissions to access this site or data is being fetched.";
}
}
}

update data to database laragon using api

I want to update data to the database in ionic. how to make the data update. Here what I tried. I try using postmen to post the api and it appear success but the data does not change.
in api.php
public function update (Request $request)
{
$id = $request->id;
$medname = $request->medname;
$price = $request->price;
$stock = $request->stock;
$medno = $request->medno;
$ingredient = $request->ingredient;
$description = $request->description;
$addinfo = $request->addinfo;
AddMedicine:: where('medname',$medname)->update([
'id' =>$id,
'medname'=>$medname,
'price'=>$price,
'stock'=>$stock,
'medno'=>$medno,
'ingredient'=>$ingredient,
'description'=>$description,
'addinfo'=>$addinfo,
]);
$msg = "Data Updated";
$datamsg = response()->json([
'success' => $msg
]);
return $datamsg->content();
}
route
Route::put('/update','ApiController#update');
Are you sure use PUT request ? Because need to CSRF token please inspect
https://stackoverflow.com/questions/30756682/laravel-x-csrf-token-mismatch-with-postman

why the session is lost after redirect in laravel 5.5?

I implementing a payment gateway with flywire in laravel.
i have a method that update a data to a crm without problem, i need this data when is called to another method that make a redirect to a external url (is a wizard) the trouble is that after maked the redirection the value of sessions are lost.
How can I holding those values ​​after redirecting to an external url?
use Session;
public function update(Request $request)
{
//code..
Session::put('value1',$request->val1);
Session::put('value2',$request->val2);
$url = 'https://www.urldemo.payment.com/payment/';
$data=[
'value1'= $request->val1,
'value2' = $request->val2,
];
$params = json_encode($data);
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$params);
try{
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
curl_close($curl);
return response()->json(['success'=>'the update was completed success','url'=> $url],200);
}catch(Exception $e){
return response()->json(['errors'=> $e->getMessage()],422);
}
}
/*This function retrieve the response data from the payment update*/
public function returnData(Request $request){
$obj = json_decode($request->getContent());
if(Session::exists('value1')){
$p1 = $obj->id;
}elseif(Session::exists('value2')){
$p2 = $obj->id;
}else{
$p1 = '';
$p2 = '';
}
$data2 = [
'value1' => $p1,
'value2' => $p2,
];
$values = json_encode($data2);
dd($values);
/*Here print the $p1 and $p2 empty thats after redirect to a external url the point is that here the session is lost*/
}
My question at this moment is how can i hold the sessions after redirect in Laravel 5.5 ?

An uncaught Exception was encountered Type: Twilio\Exceptions\RestException

I am using SDK of Twilio messaging service and they provided functionality to verify phone/mobile numbers, it is working good if number is valid, but giving
An uncaught Exception was encountered Type:
Twilio\Exceptions\RestException
If number is not valid, after getting this error my function stop working. I am using codeigniter to call its SDK functions,
Please help me how to handle this error.
public function verify($contact_no){
$sid = "AccountSID";
$token = "Token";
$client = new Client($sid, $token);
$encoded = rawurlencode("$contact_no");
$number = $client->lookups
->phoneNumbers($encoded)
->fetch(
array("countryCode" => "US")
);
if ($number->phoneNumber) {
echo "True";
$status = "valid";
} else {
echo "False";
$status = 'invalid';
}
$data = array(
"verify" => "$status"
);
$this->model->update_contact_verification($contact_no, $data);
}
Twilio developer evangelist here.
When the number is not recognised as a number, the Lookup API returns a 404. The PHP helper library throws a RestException for that, so you need to catch the error. You should update your code to something like this:
public function verify($contact_no){
$sid = "AccountSID";
$token = "Token";
$client = new Client($sid, $token);
$encoded = rawurlencode("$contact_no");
try {
$number = $client->lookups
->phoneNumbers($encoded)
->fetch(
array("countryCode" => "US")
);
echo $number->phoneNumber;
$status = 'valid';
} catch (Twilio\Exceptions\RestException $e) {
echo "False";
$status = 'invalid';
}
$data = array(
"verify" => "$status"
);
$this->model->update_contact_verification($contact_no, $data);
}
Let me know if that helps at all.

facebook app losing session values after redirection

I am using Facebook PHP SDK 3.1.1
This page is supposed to collect value from header and later use it for uploading images.
Problem: $_SESSION['file'] becomes null after user logs in to Facebook.
<?php
require 'facebook.php';
include('connect.php');
$facebook = new Facebook(array('appId' => "XXXXXX",'secret' => "XXXXX","cookie" => true,'fileUpload' => true));
session_start();
$user_id = $facebook->getUser();
if(isset($_REQUEST["src"]))
{
echo "<center><img src='loader.gif'/></center>";
echo "<center><div id='msg'>Exporting Image..</div></center>";
$_SESSION['file'] = $_REQUEST["src"];
$_SESSION['club'] = $_REQUEST["club"];
}
$code = $_REQUEST["code"];
if(empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=". $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
exit();
}
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url). "&client_secret=" . $app_secret . "&scope=user_photos,email,read_stream,publish_stream&code=".$code;
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$response = url_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=". $params['access_token'];
$user = json_decode(url_get_contents('https://graph.facebook.com/me/albums?access_token='.$params['access_token']),true);
foreach($user as $key=>$value)
{
foreach($user[$key] as $key1=>$value1)
{
if($value1['name'] == "Photos")
{
$album_uid = $value1['id'];
}
}
}
if(!isset($album_uid))
{
echo 'Create an album';
$album_details = array(
'message'=> 'Uploaded via XXX',
'name'=> 'Photos'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
}
$photo_details = array('message'=>$_SESSION["club"]);
try{
$file = NULL;
$file="../Photos/".$_SESSION['file'].".jpeg";
echo '<script>document.getElementById("msg").innerHTML = "Uploading Image"</script>';
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
}catch(Exception $e){
echo "<script type='text/javascript'>top.location.href = 'http://www.facebook.com/PAGE_URL/';</script>";
exit();
}
$_SESSION['file'] is null
Am I doing it right ? or something is wrong with my web hosting ?
The problem is that your app is running inside of an IFRAME and the session cookies are not being preserved. Please see here:
Facebook Iframe App with multiple pages in Safari Session Variables not persisting

Resources