How to grab contacts from gmail using google API's and contact grabber in PHP? - api

In my project i want to grab the contacts from gmail using google API's. I provide three keys such as client id, client secret and signature key. When i trying to get contacts the pop-up window is showing error message "Signature key must be formatted". What i have done wrong? Thanks in advance.
Here is my code
keyConfig.php
<?php
$apiRequestUrl = "https://stescodes.com/api/contactsapi.aspx"; // StesCodes contact grabber API request url
$originalsignaturekey = "lxFWDA5ng36sdvlFGukof75vyi";//replace with your signature key
$gmailConsumerKey = "1009516162377-n5s7lo5b4dvlt8e7s3rt12f8i02lpk1f.apps.googleusercontent.com";
$gmailConsumerSecret = "raCUba1smsZCzrVNjqFIqiqC";
$YahooConsumerKey = "your yahoo api key";
$YahooConsumerSecret = "your yahoo api key";
$LiveConsumerKey = "your live api key";
$LiveConsumerSecret = "your live api key";
$fbConsumerKey = "your facebook api key";
$fbConsumerSecret = "your facebook api key";
$callbackurl = "http://localhost/grab/oauth.php";// eg: return url after user authentication http://yourdomain/oauth.php
$currentdirpath = "http://dev.stescodes.com/";//your current web directory path eg:http://yourdomain/
?>
oauth.php
<?php
session_start();
?>
<?php include 'keyConfig.php'; ?>
<html>
<head><title></title>
<script>
function redirectrequest(a)
{
window.location = a;
}
function closepopup(a,b,c,d) {
window.opener.startGrabbingContactsOauth(a,b,c,d);
window.self.close();
}
</script>
</head>
<body>
<?php
$servicename = "gmail";
$token = "";
$ConsumerKey = "";
$ConsumerSecret="";
$tokensecret="";
$tokenverifier="";
$flag=0;
$parameters="";
if($_GET['currpage']!=null)
$_SESSION['currpage']=$_GET['currpage'];
if($_SESSION['currpage']=="gmail")
{
$servicename = "gmail";
$ConsumerKey = $gmailConsumerKey;
$ConsumerSecret = $gmailConsumerSecret;
if ($_GET['code'] != null)
{
$token = $_GET['code'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="yahoo")
{
$servicename = "yahoo";
$ConsumerKey = $YahooConsumerKey;
$ConsumerSecret = $YahooConsumerSecret;
if (($_GET['oauth_token'] != null) && ($_GET['oauth_verifier'] != null))
{
$token = $_GET['oauth_token'];
$tokenverifier = $_GET['oauth_verifier'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="facebook")
{
$servicename = "facebook";
$ConsumerKey = $fbConsumerKey;
$ConsumerSecret = $fbConsumerSecret;
if (($_GET['code'] != null))
{
$token = $_GET['code'];
$tokenverifier = "";
$tokensecret = "";
$flag = 1;
}
}
else if(($_SESSION['currpage']=="msn") || ($_SESSION['currpage']=="hotmail") || ($_SESSION['currpage']=="msnmessenger"))
{
$servicename = $_SESSION['currpage'];
$ConsumerKey = $LiveConsumerKey;
$ConsumerSecret = $LiveConsumerSecret;
//Live settings
if ($_GET["code"] != null)
{
$token = $_GET["code"];
$flag = 1;
}
}
if ($flag == 1)
{
$parameters = "type=accesstoken&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) . "&Token=" . urlencode($token) . "&TokenSecret=" . urlencode($tokensecret) . "&TokenVerifier=" . urlencode($tokenverifier);
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $_SESSION['tokenverifier'];
$_SESSION["consumerkey"] = $ConsumerKey;
$_SESSION["consumersecret"] = $ConsumerSecret;
echo "<SCRIPT LANGUAGE=\"javascript\"> closepopup('".$servicename."',". $result .",'".$ConsumerKey."','".$ConsumerSecret."');</SCRIPT>";
}
else
{
$parameters = "type=authenticationurl&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) ;
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $tokenverifier;
echo "<SCRIPT LANGUAGE=\"javascript\"> redirectrequest('".$authdetails[details][authUrl]."'); </SCRIPT>";
}
?>

Related

How to update youtube annalytics to all previously registered youtube channels

I have a web app in which the users can register and connect their youtube channels. Next in the registration process I collect all the information I can get from youtube data api and youtube analytics and reporting api (with scopes and access tokens) and store it in the database. I show that info on their dashboards. I also display that info in the admin panel for the administrators to see.
The problem is, how can I refresh that info, lets say, once a day? I've tried with the access token but i get error 403 Forbidden message. I want to update the info to all of the registered youtube accounts, this is the function I use to update all but its not working
(In the bellow script, i send $code as a variable and the function is called on the redirect URI)
$youtube_channels = YouTubeChannels::get();
$key = env('NEW_YOUTUBE_API_KEY');
foreach($youtube_channels as $youtube_channel) {
$yt_channel_statistics = Http::get('https://www.googleapis.com/youtube/v3/channels', [
'part' => 'statistics,snippet',
'id' => $youtube_channel->youtube_channel_id,
'key' => $key
]);
$yt_channel_statistics_json = $yt_channel_statistics->json();
$update_yt = YouTubeChannels::where('youtube_channel_id', $youtube_channel->youtube_channel_id)->first();
if($update_yt != null) {
$update_yt->channel_name = $yt_channel_statistics_json['items'][0]['snippet']['title'];
$update_yt->channel_subscribers = $yt_channel_statistics_json['items'][0]['statistics']['subscriberCount'];
$update_yt->channel_total_views = $yt_channel_statistics_json['items'][0]['statistics']['viewCount'];
$update_yt->channel_videos_count = $yt_channel_statistics_json['items'][0]['statistics']['videoCount'];
$update_yt->save();
}
//test
$baseUrl = 'https://www.googleapis.com/youtube/v3/';
$apiKey = env('NEW_YOUTUBE_API_KEY');
$channelId = $youtube_channel->youtube_channel_id;
$params = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $apiKey
];
$url = $baseUrl . 'channels?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$params = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> '50',
'key'=> $apiKey
];
$url = $baseUrl . 'playlistItems?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos = [];
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
while(isset($json['nextPageToken'])){
$nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
$json = json_decode(file_get_contents($nextUrl), true);
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
}
$video_ids_string = collect($videos)->implode(',');
//
//endtest
//new test
//
$params = [
'part'=> 'snippet,contentDetails,statistics,status',
'id' => $video_ids_string,
'key'=> $apiKey
];
$url = $baseUrl . 'videos?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos_infos = $json;
//
YouTubeVideos::where('youtube_channel_id', $youtube_channel->id)->delete();
foreach ($videos as $video){
foreach($videos_infos['items'] as $info){
if ($info['id'] == $video) {
if($info['status']['privacyStatus'] == 'public') {
$youtube_video = new YouTubeVideos();
// if (!$live_error) {
// foreach ($live_videos as $live) {
// if ($live->youtube_id == $video) {
// $youtube_video->was_live = true;
// }
// }
// }
// dd($video);
$youtube_video->youtube_channel_id = $youtube_channel->id;
$youtube_video->yt_video_id = $video;
$youtube_video->yt_video_title = $info['snippet']['title'];
$youtube_video->yt_video_description = $info['snippet']['description'];
$youtube_video->yt_video_published_at = Carbon::parse($info['snippet']['publishedAt']);
if(isset($info['snippet']['defaultAudioLanguage'])) {
$youtube_video->yt_video_default_audio_language = $info['snippet']['defaultAudioLanguage'];
} else {
$youtube_video->yt_video_default_audio_language = '';
}
if (strcmp($info['contentDetails']['caption'], 'true') == 0) {
$youtube_video->is_video_captioned = true;
} else {
$youtube_video->is_video_captioned = false;
}
$youtube_video->yt_video_definition = $info['contentDetails']['definition'];
$youtube_video->yt_video_dislike_count = 0;
$youtube_video->yt_video_like_count = $info['statistics']['likeCount'];
$youtube_video->yt_video_views_count = $info['statistics']['viewCount'];
//proba type of views
//
$client = new Google_Client();
try{
$client->setAuthConfig(storage_path('app'.DIRECTORY_SEPARATOR. 'json'. DIRECTORY_SEPARATOR.'client_secret.json'));
}catch (\Google\Exception $e){
dd($e->getMessage());
}
// $client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/youtube.readonly']);
$client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL,GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, GOOGLE_SERVICE_YOUTUBE::YOUTUBEPARTNER,'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly']);
$client->setRedirectUri(env('APP_URL') . '/get_access_token_yt_test');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setPrompt("consent");
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true); // incremental auth
if (!isset($code)){
$auth_url = $client->createAuthUrl();
return redirect()->away($auth_url)->send();
}else{
if($code != null) {
$client->fetchAccessTokenWithAuthCode($code);
$client->setAccessToken($client->getAccessToken());
session()->push('refresh_token_youtube', $client->getRefreshToken());
session()->save();
}
}
$service = new Google_Service_YouTube($client);
$analytics = new Google_Service_YouTubeAnalytics($client);
$typeOfViews = $analytics->reports->query([
'ids' => 'channel==' . $youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'views',
'dimensions' => 'liveOrOnDemand',
'filters' => 'video=='.$video
]);
foreach ($typeOfViews as $viewType) {
if ($viewType[0] == 'ON_DEMAND') {
$youtube_video->yt_video_on_demand_views_count = $viewType[1];
} else if ($viewType[0] == 'LIVE') {
$youtube_video->yt_video_live_views_count = $viewType[1];
}
}
$watch_times = $analytics->reports->query([
'ids' => 'channel=='.$youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'estimatedMinutesWatched',
'dimensions' => 'day',
'filters' => 'video=='.$video
]);
// //update quotas
// // self::update_quotas(1);
$total = 0;
foreach ($watch_times as $watch_time){
$total += $watch_time[1];
}
$youtube_video->estimated_minutes_watch_time = $total;
$youtube_video->save();
//zacuvuva captions
$xmlString = file_get_contents("https://video.google.com/timedtext?type=list&v=" . $video);
$xmlObject = simplexml_load_string($xmlString);
$json = json_encode($xmlObject);
$phpArray = json_decode($json, true);
if (isset($phpArray['track'])) {
foreach ($phpArray['track'] as $array) {
$yt_video_captions = new YouTubeVideosCaptions();
$yt_video_captions->youtube_video_id = $youtube_video->id;
$yt_video_captions->language = $array['lang_code'];
$yt_video_captions->save();
}
}
//zacuvuva tags
if(isset($info['snippet']['tags'])) {
if ($info['snippet']['tags'] != null) {
foreach ($info['snippet']['tags'] as $tag) {
$youtube_video_tags = new YouTubeVideosTags();
$youtube_video_tags->youtube_video_id = $youtube_video->id;
$youtube_video_tags->tag = $tag;
$youtube_video_tags->save();
}
}
}
if ($youtube_video->is_video_captioned) {
$captions = YouTubeVideosCaptions::where('youtube_video_id', $youtube_video->id)->get();
foreach ($captions as $caption) {
$video_id = YouTubeVideos::where('id', $caption->youtube_video_id)->first();
$client->authorize();
$fp = fopen('../storage/app/captions/' . $caption->id . '.xml', 'w');
$xmlString = file_get_contents("http://video.google.com/timedtext?type=track&v=" . $video_id['yt_video_id'] . "&id=0&lang=" . $caption['language']);
fwrite($fp, $xmlString);
fclose($fp);
}
}
echo 'done';
}
}
}
}
// Command::line('Youtube videos updated');
//
//
//end new test
}
}

How to get the Gross Sales from the Square Order API?

Qn1) I have tried getting the gross sales from the Order API. However, I could only be able to get each lineitem gross value concatenating with one and another ...
Gross value that is concatenating
Qn2) I tried to echo all the item name, qty and etc to insert it into my database although it works but I am getting an error message shown below
Error message
Here is my code: (Have replaced the access token and the location_id to 'XXXX')
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
echo (array_sum($grossSales)/100); //Qn1
echo($orderid. " ". $lineItemsID ." ".$catalogObjID." ".$itemName ." ".$itemQty." <br/>"); //Qn2
}
}
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
$grossSales = array();
if (is_array($orders) || is_object($orders)) {
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
if (is_array($lineItems) || is_object($lineItems)){
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
}
}
}
}
$sum = 0;
foreach($grossSales as $key=>$value)
{
$sum+= $value;
}
echo ($sum/100);
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>

get table rate shipping data in Woocommerce REST API

I am trying to get all active shipping methods in Woocommerce REST API. How can I achieve this. I am new to woocommerce REST API, Any help is much appreciated.
I want response something like this -
{
"shipping_methods": {
"method_id": "method_title"
}
}
I , finally, come up with the solution. It may help others.
Below is complete code to get all table rate shipping data including shipping zones, shipping methods by zone and rates by zone -
header('Content-type: application/json');
$json_file=file_get_contents('php://input');
$jsonvalue= json_decode($json_file,true);
global $wpdb;
global $woocommerce;
$active_methods = array();
$shipping_methods = $woocommerce->shipping->load_shipping_methods();
//echo "<pre>";print_r($shipping_methods);
foreach ( $shipping_methods as $id => $shipping_method ) {
if ( isset( $shipping_method->enabled ) && 'yes' === $shipping_method->enabled ) {
$data_arr = array( 'title' => $shipping_method->title, 'tax_status' => $shipping_method->tax_status );
if($id=='table_rate'){
$raw_zones = $wpdb->get_results("SELECT zone_id, zone_name, zone_order FROM {$wpdb->prefix}woocommerce_shipping_zones order by zone_order ASC;");
//echo "<pre>";print_r($raw_zones);
$shipping = array();
$shippingarr = array();
foreach ($raw_zones as $raw_zone) {
$zones = new WC_Shipping_Zone($raw_zone->zone_id);
$zone_id = $zones->zone_id;
$zone_name = $zones->zone_name;
$zone_enabled = $zones->zone_enabled;
$zone_type = $zones->zone_type;
$zone_order = $zones->zone_order;
$shipping['zone_id'] = $zone_id;
$shipping['zone_name'] = $zone_name;
$shipping['zone_enabled'] = $zone_enabled;
$shipping['zone_type'] = $zone_type;
$shipping['zone_order'] = $zone_order;
$shipping_methods = $zones->shipping_methods;
foreach($shipping_methods as $shipping_method){
$methodid = $shipping_method["number"];
$raw_rates[$methodid]['rates'] = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}woocommerce_shipping_table_rates WHERE shipping_method_id={$methodid};",ARRAY_A);
}
$shipping['shipping_methods'] = $raw_rates;
$raw_country = $wpdb->get_results("SELECT location_code FROM {$wpdb->prefix}woocommerce_shipping_zone_locations WHERE zone_id={$zone_id};",ARRAY_N);
$shipping['countries'] = $raw_country;
$shippingarr[] = $shipping;
}
$data_arr['shipping_zones'] = $shippingarr;
}
$active_methods[ $id ] = $data_arr;
}
}
if(!empty($shippingarr)){
$result['success']='true';
$result['error']="0";
$result['msg']='Shipping methos found.';
$result['data']=$active_methods;
}else{
$result['success']='true';
$result['error']="0";
$result['msg']='Shipping methos found.';
$result['data']= array();
}
echo json_encode($result); `

Magento: listing products from API

This is my script I have used from Magento Reference (see: RequestToken Retrieve the list of products for Admin user with OAuth authentication)
I am submiting this script from my localhost.
/**
* Example of retrieving the products list using Admin account via Magento REST API. OAuth authorization is used
* Preconditions:
* 1. Install php oauth extension
* 2. If you were authorized as a Customer before this step, clear browser cookies for 'yourhost'
* 3. Create at least one product in Magento
* 4. Configure resource permissions for Admin REST user for retrieving all product data for Admin
* 5. Create a Consumer
*/
// $callbackUrl is a path to your file with OAuth authentication example for the Admin user
$callbackUrl = "http://yourhost/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://yourhost/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://yourhost/admin/oAuth_authorize';
$accessTokenRequestUrl = 'http://yourhost/oauth/token';
$apiUrl = 'http://yourhost/api/rest';
$consumerKey = 'yourconsumerkey';
$consumerSecret = 'yourconsumersecret';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "<br/>";
print_r($e->lastResponse);
}
As a result I am getting "Whoops, our bad..." page, I was expecting to see list of products.
In the URL I am seeing oauth_token.
http://myUrl/oAuth_authorize?oauth_token=a4315776966dca4fa5d3786f4fghjkab157cf
Can somebody point me out what to do next? If you need any additional data, please ask.
There is a typo in url
$adminAuthorizationUrl = 'http://yourhost/admin/oAuth_authorize';
should be
$adminAuthorizationUrl = 'http://yourhost/admin/oauth_authorize';

Youtube api upload videos not working "Error : NoLinkedYouTubeAccount "

am using youtube api to upload videos from my website, this is first time am using am got stuck with the google account.I gave youtube account username, password and developer key am getting the error "NoLinkedYouTubeAccount ".
Some one help me to fix this issue.
/**
* developerKey
*/
public $developerKey;
/**
* accessToken - authorization access taken
*/
public $accessToken;
/**
* next_index - used to track short results
*/
public $next_index;
/**
* authType - authentication type GoogleLogin or AuthSub
*/
public $authType;
/**
* initializes the token and API key information for API methods which requires authentication information
* #param developerKey - String
* #param accessToken - array
* #return void
* #access public
* Modified: Sandip
*/
public function __construct($params){
$this->accessToken = $params['accessToken'];
$this->authType = $params['authType'];
$this->developerKey=$params['developerKey'];
}
/**
* client login authentication
* #param username - String
* #param pass - String
* #return array
* #access public
* Modified: Sandip
*/
public function clientLoginAuth($username,$pass){
$this->authType = 'GoogleLogin';
$url = 'https://www.google.com/youtube/accounts/ClientLogin';
$data = 'Email='.urlencode($username).'&Passwd='.urlencode($pass).'&service=youtube&source=Test';
$result = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlheader[0] = "Content-Type:application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
$result['output'] = curl_exec($ch);
$result['err'] = curl_errno( $ch );
$result['errmsg'] = curl_error( $ch );
$result['header'] = curl_getinfo( $ch );
$temp = explode("YouTubeUser=",$result['output']);
$result['username'] = trim($temp[1]);
$temp2 = explode("=",trim($temp[0]));
$result['token'] = trim($temp2[1]);
$this->accessToken = $result['token'];
curl_close($ch);
return $result;
}
public function uploadVideo($filename,$fullFilePath,$title,$description,$tags)
{
$fdata = file_get_contents($fullFilePath);
$tmpdata = '<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<media:title type="plain">'.$title.'</media:title>
<media:description type="plain">'.$description.'</media:description>
<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category> <media:keywords>'.$tags.'</media:keywords>
</media:group>
</entry>
';
$url = 'http://gdata.youtube.com/feeds/api/users/default/uploads';
$data = '--f93dcbA3
Content-Type: application/atom+xml; charset=UTF-8
'.$tmpdata.'
--f93dcbA3
Content-Type: video/quicktime
Content-Transfer-Encoding: binary
'.$fdata.'
--f93dcbA3--';
$token = $this->accessToken;
$developerKey = $this->developerKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlheader[0] = "Host: uploads.gdata.youtube.com";
if($this->authType == 'GoogleLogin')
$curlheader[1] = "Authorization: ".$this->authType." auth=\"$token\"";
else
$curlheader[1] = "Authorization: ".$this->authType." token=\"$token\"";
$curlheader[2] = "GData-Version: 2";
$curlheader[3] = "X-GData-Key: key=\"$developerKey\"";
$curlheader[4] = "Slug: ".$filename;
$curlheader[5] = "Content-Type: multipart/related; boundary=\"f93dcbA3\"";
$curlheader[6] = "Content-Length: ".strlen($data);
$curlheader[7] = "Connection: close";
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
//print_r($info);
curl_close($ch);
unset($fdata);
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$webSite = 'http://www.youtube.com/';
$criteria = 'uploads';
$mediaInfo = array();
$gdMedia = $xml->children('http://schemas.google.com/g/2005');
$media = $xml->children('http://search.yahoo.com/mrss/');
$ytMedia = $xml->children('http://gdata.youtube.com/schemas/2007');
$georssMedia = $xml->children('http://www.georss.org/georss');
if($media->group->title){
$mediaInfo['title'] = sprintf("%s",$media->group->title[0]);
}else{
$mediaInfo['title'] = '';
}
if($media->group->description){
$mediaInfo['description'] = sprintf("%s",$media->group->description[0]);
}else{
$mediaInfo['description'] = '';
}
if($media->group->player){
$video = $media->group->player[0]->attributes()->url;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', $test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
}else{
if($entry->link[0]->attributes()->href){
$video = $entry->link[0]->attributes()->href;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', $test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
}else{
return "video not found.";
}
}
$mediaInfo['path_url'] = $mediaInfo['contentUrl'];
$mediaInfo['webSite'] = $webSite;
$mediaInfo['genre'] = sprintf("%s",#$media->group->category[0]);
$mediaInfo['criteria'] = $criteria;
unset($xml);
unset($gdMedia);
unset($media);
unset($ytMedia);
unset($georssMedia);
return $mediaInfo;
}
else
{
$result = array();
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
unset($validresult);
return $result;
}
}
public function getUploadedVideos($username='default',$startIndex=1,$limit=10,$location='',$location_radius='',$safeSearch='strict',$strict='true'){
$url = 'http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?start-index='.$startIndex.'&max-results='.$limit.'&strict='.$strict;
if($location !='')
{
$url .= '&location='.$location;
$url .= '&location-radius='.$location_radius;
}
//echo "<br>".$url;
$criteria = 'uploads';
if($username == 'default')
$output = $this->make_api_call($url);
else
{
$response = $this->make_get_call($url);
$output = $response['output'];
}
$result = array();
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$tmp = $xml->xpath("openSearch:totalResults");
$tmp_totalresults = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:startIndex");
$result['startindex'] = (string)$tmp[0];
//$tmp = $xml->xpath("openSearch:itemsPerPage");
//$result['itemsPerPage'] = (string)$tmp[0];
$res = $this->getFormatedVideoresult($xml,$criteria);
//Pagination logic
$shortCnt = $this->getShortCount();
//
if($shortCnt > 0 && $tmp_totalresults > $limit)
{
$newStartIndex = $startIndex + $limit;
$newmaxresults = $shortCnt;
$iteration = 1;
while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){
if($iteration !=1){
$newStartIndex = $newStartIndex + $newmaxresults;
$newmaxresults = $shortCnt;
}
$iteration++;
$url = 'http://gdata.youtube.com/feeds/api/users/'.$username.'/uploads?start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
if($location !='')
{
$url .= '&location='.$location;
$url .= '&location-radius='.$location_radius;
}
$shortResult = $this->getShortResult($url,$criteria);
if(#$shortResult['is_error']=='No'){
if(!empty($shortResult['result']))
{
////echo "<br>INSIDE";
foreach($shortResult['result'] as $shortkey => $shortItem)
$res[] = $shortItem;
$shortCnt = $this->getShortCount();
}
else
{
continue;
}
}
else
{
break;
}
}//while
$result['nextPageIndex'] = #(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
}
else
{
$result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
}
if($tmp_totalresults < $result['nextPageIndex'])
{
$result['nextPageIndex'] = 0;
}
//pagination logic
$result['itemsPerPage'] = $limit;
$result['totalresults'] = count($res);
$result['result'] = $res;
unset($res);
unset($xml);
}
else
{
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
}
unset($validresult);
return $result;
}
public function checkErrors($response){
$result = array();
$result['is_error'] = 'No';
$reg_ex = '/<H1>Bad Request<\/H1>/';
$res = preg_match_all($reg_ex,$response,$matches);
if(!empty($matches[0])) {
$result['is_error'] = 'Yes';
$result['error'] = "Bad Request";
}
else {
$xml = #simplexml_load_string($response);
if($xml === FALSE && $response !=''){
$result['error'] = $response;
$result['is_error'] = 'Yes';
}
else{
if(#$xml->error){
$msg = #(string)$xml->error->code.':'.#(string)$xml->error->internalReason;
unset($xml);
$result['error'] = $msg;
$result['is_error'] = 'Yes';
}
else{
$result['xml'] = $xml;
}
}
}
unset($xml);
unset($response);
return $result;
}
public function getContentURL($url){
$output = $this->make_api_call($url);
$result = array();
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$ytMedia = $xml->children('http://gdata.youtube.com/schemas/2007');
$result['term'] = $xml->category[1]->attributes()->term;
$result['title'] = (string)$xml->title;
$result['username'] = (string)$ytMedia->username;
$result['contentURL'] = (string)$xml->content->attributes()->src;
if(stristr($result['title'],'Activity of'))
{
$result['contentURL'] = 'http://gdata.youtube.com/feeds/api/users/'.$result['username'].'/uploads?v=2';
}
}
else
{
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
}
unset($validresult);
return $result;
}
public function getRecentUploadedVideos($xml){
$i = 0;
$res = array();
foreach($xml->entry as $fentry){
$i++;
$term = $fentry->category[1]->attributes()->term;
if($term == 'video_uploaded')
{
$mediaInfo = array();
$entry = $fentry->link[1]->entry;
$gdMedia = $entry->children('http://schemas.google.com/g/2005');
$media = $entry->children('http://search.yahoo.com/mrss/');
$ytMedia = $entry->children('http://gdata.youtube.com/schemas/2007');
$georssMedia = $entry->children('http://www.georss.org/georss');
if($gdMedia->rating){
$rating = (string)$gdMedia->rating->attributes();
$mediaInfo['rating'] = $rating['average'];
}else{
$mediaInfo['rating'] = 0;
}
if($media->group->thumbnail){
$mediaInfo['iconImage'] = sprintf("%s",$media->group->thumbnail[0]->attributes()->url);
}else{
$mediaInfo['iconImage'] = '';
}
if($media->group->title){
$mediaInfo['title'] = sprintf("%s",$media->group->title[0]);
}else{
$mediaInfo['title'] = '';
}
if($media->group->description){
$mediaInfo['description'] = sprintf("%s",$media->group->description[0]);
}else{
$mediaInfo['description'] = '';
}
if($media->group->player){
$video = $media->group->player[0]->attributes()->url;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', #$test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
}
else{
$tmp = #$entry->xpath("app:control");
$tmp2 = #$tmp[0]->xpath("yt:state");
if(#$tmp2[0]->attributes()->name == 'restricted')
{
//echo "<br>INSIDE ".$mediaInfo['title'];
$this->next_index[$i] = 'n';
continue;
}
if(isset($entry->link) && $entry->link[0]->attributes()->href !=''){
$video = $entry->link[0]->attributes()->href;
$vLink = preg_replace('/=/', "/", $video);
$videoLink = preg_replace('/\?/', "/", $vLink);
$mediaInfo['contentUrl'] = $videoLink."&hl=en&fs=1";
$test_str = preg_split('/\/v\//', $videoLink, 2);
$video_id_array = preg_split('/&/', $test_str[1],2);
$mediaInfo['videoId'] = $video_id_array[0];
if(!$mediaInfo['videoId'])
{
$this->next_index[$i] = 'n';
//echo "video Skipped.";
continue;
}
}
else{
$this->next_index[$i] = 'n';
continue;
}
}
$this->next_index[$i] = 'y';
$res[] = $mediaInfo;
}
else
{
$this->next_index[$i] = 'n';
}
} // foreach
return $res;
}
public function getRecentShortResult($url){
$token = $this->accessToken;
$developerKey = $this->developerKey;
if($token !='' && $developerKey !='')
$output = $this->make_api_call($url);
else
{
$response = $this->make_get_call($url);
$output = $response['output'];
}
$result = array();
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No')
{
$xml = $validresult['xml'];
$tmp = $xml->xpath("openSearch:totalResults");
$tmp_totalresults = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:startIndex");
$result['startindex'] = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:itemsPerPage");
$result['itemsPerPage'] = (string)$tmp[0];
//$result['itemsPerPage'] = $maxresults;
if($tmp_totalresults > $result['startindex']){
$res = $this->getRecentUploadedVideos($xml);
$result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
}
else
$result['nextPageIndex'] = 0;
$result['result'] = #$res;
}
else
{
$result['error'] = $validresult['error'];
}
$result['is_error'] = $validresult['is_error'];
unset($validresult);
unset($output);
unset($response);
return $result;
}
public function getVideosBysubscriptionID($subscriptionID,$startIndex=1,$limit=10,$safeSearch='strict',$strict='true'){
$url = 'http://gdata.youtube.com/feeds/api/users/default/subscriptions/'.$subscriptionID.'?v=2';
$feedResponse = $this->getContentURL($url);
$contentURL = #$feedResponse['contentURL'];
$tempcontentURL = $contentURL;
$contentURL .= '&start-index='.$startIndex.'&max-results='.$limit.'&strict='.$strict;
$result = array();
if($contentURL !=''){
$output = $this->make_api_call($contentURL);
$validresult = $this->checkErrors($output);
if($validresult['is_error'] == 'No'){
$xml = $validresult['xml'];
$tmp = $xml->xpath("openSearch:totalResults");
$tmp_totalresults = (string)$tmp[0];
$tmp = $xml->xpath("openSearch:startIndex");
$result['startindex'] = (string)$tmp[0];
if(#$feedResponse['recentUpload'] == 1){
$res = $this->getRecentUploadedVideos($validresult['xml']);
$shortCnt = $this->getShortCount();
if($shortCnt > 0 && $tmp_totalresults > $limit)
{
$newStartIndex = $startIndex + $limit;
$newmaxresults = $shortCnt;
$iteration = 1;
while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){
if($iteration !=1){
$newStartIndex = $newStartIndex + $newmaxresults;
$newmaxresults = $shortCnt;
}
$iteration++;
$url = $tempcontentURL.'&start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
$shortResult = $this->getRecentShortResult($url);
if(#$shortResult['is_error']=='No'){
if(!empty($shortResult['result']) && count($res) <= $limit)
{
foreach($shortResult['result'] as $shortkey => $shortItem)
$res[] = $shortItem;
$shortCnt = $this->getShortCount();
}
else
{
continue;
}
}
else
{
break;
}
}//WHILE
$result['nextPageIndex'] = #(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
}
else
{
$result['nextPageIndex'] = #$result['startindex'] + count($this->next_index);
}
if($tmp_totalresults < $result['nextPageIndex'])
{
$result['nextPageIndex'] = 0;
}
$result['itemsPerPage'] = $limit;
$result['totalresults'] = count($res);
$result['result'] = $res;
unset($res);
unset($xml);
}
else
{
$criteria = $feedResponse['title'];
$xml = $validresult['xml'];
$res = $this->getFormatedVideoresult($xml,$criteria);
//Pagination logic
$shortCnt = $this->getShortCount();
if($shortCnt > 0 && $tmp_totalresults > $limit)
{
$newStartIndex = $startIndex + $limit;
$newmaxresults = $shortCnt;
$iteration = 1;
while($shortCnt > 0 && $tmp_totalresults >= $newStartIndex){
if($iteration !=1){
$newStartIndex = $newStartIndex + $newmaxresults;
$newmaxresults = $shortCnt;
}
$iteration++;
$url = $tempcontentURL.'&start-index='.$newStartIndex.'&max-results='.$newmaxresults.'&strict='.$strict;
$shortResult = $this->getShortResult($url,$criteria);
if(#$shortResult['is_error']=='No'){
if(!empty($shortResult['result']))
{
foreach($shortResult['result'] as $shortkey => $shortItem)
$res[] = $shortItem;
$shortCnt = $this->getShortCount();
}
else
{
continue;
}
}
else
{
break;
}
}//while
$result['nextPageIndex'] = #(isset($shortResult['nextPageIndex'])?$shortResult['nextPageIndex']:0);
}
else
{
$result['nextPageIndex'] = $result['startindex'] + count($this->next_index);
}
if($tmp_totalresults < $result['nextPageIndex'])
{
$result['nextPageIndex'] = 0;
}
//pagination logic
$result['itemsPerPage'] = $limit;
$result['totalresults'] = count($res);
$result['result'] = $res;
unset($res);
unset($xml);
}
}// NO
else
{
$result['is_error'] = $validresult['is_error'];
$result['error'] = $validresult['error'];
}
}
else
{
$result['is_error'] = $feedResponse['is_error'];
$result['error'] = $feedResponse['error'];
}
unset($validresult);
unset($feedResponse);
return $result;
}
}
/* End of file Someclass.php */
Thanks.
For anyone that comes across this, I had this error and fixed it by logging into YouTube as the main user, going to the top right and clicking 'Youtube Settings'. Then I clicked 'create channel'. Error gone!
This doesn't have anything to do with your code or program. It simply means you have not linked your Google account with Youtube, or vice versa.
I encountered the same problem too. But for me, I initially created a Google account, and even though when I went to Youtube.com I could see that I was logged it, but that did not mean that my Google account was actually linked to YouTube yet. So in my case, when I was on youtube.com, I actually clicked on my username in the upper right corner and did something...but basically it just prompted me to link YouTube to my Google account. When that was all done, it finally took me to my YouTube profile page. And then when I ran my program again, the "NoLinkedYoutubeAccount" error message was gone.
Give that a try. For you, it might be the opposite. Hope this helps!