PHP youtube api error - php

How to upload videos using youtube api from localhost web application in codeigniter or php?
I followed the steps in youtube library as follows:
api key : 'my developer key'
consumer key : 'anonymous'
consumer secret : 'anonymous'
I am using the functions as follows and my site url is : http://localhost/ci-youtube/example/request_youtube
//CALL THIS METHOD FIRST BY GOING TO
//www.your_url.com/index.php/request_youtube
public function request_youtube()
{
$params['key'] = 'anonymous';
$params['secret'] = 'anonymous';
$params['algorithm'] = 'HMAC-SHA1';
$this->load->library('google_oauth', $params);
$data = $this->google_oauth->get_request_token(site_url('example/access_youtube'));
print_r($data);
$this->session->set_userdata('token_secret', $data['token_secret']);
redirect($data['redirect']);
//$this->load->view('welcome_message');
}
//This method will be redirected to automatically
//once the user approves access of your application
public function access_youtube()
{
$params['key'] = 'anonymous';
$params['secret'] = 'anonymous';
$params['algorithm'] = 'HMAC-SHA1';
$this->load->library('google_oauth', $params);
$oauth = $this->google_oauth->get_access_token(false, $this->session->userdata('token_secret'));
$this->session->set_userdata('oauth_token', $oauth['oauth_token']);
$this->session->set_userdata('oauth_token_secret', $oauth['oauth_token_secret']);
}
But it shows the error : 'Invalid Token'
Any idea ?
Thanks in advance for quick reply.

I think you still haven't got an API key from YouTube yet. Is that so?

I haven't published this yet but I'm about to release a PHP based Youtube autouploader, that allows you to run uploads from a NAS box, spare PC etc.
https://github.com/Danack/Youtube-Autouploader
It has a complete example for how to upload videos to Youtube in there, in particular the function "uploadVideo($filename, $videoInfo)"
https://github.com/Danack/Youtube-Autouploader/blob/master/youtubeCurl.php

First make sure you are using the correct consumer key and consumer secret.
Second if you run into problems with either the Google_oauth library or the Youtube library make sure you set the DEBUG constant in those libraries to true. Doing that will dump a lot more logging information in to the PHP error log which should help you diagnose the problem.

Timestamp is too far from current time:
It seems like your server time is not correctly set. Please correct your server time, you may want to restart your web server after fixing the time. - Change Server time. Try restart Webserver first. If not work, restart your Computer ==> it work!.

Related

php openid connect get token

I try to use jumbojett library for php and openid. I made connection but and get secret id and client, but when I want to get token I don't know how.
In small documentation is next example:
$oidc = new OpenIDConnectClient('https://id.provider.com',
'ClientIDHere',
'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');
// this assumes success (to validate check if the access_token property is there and a valid JWT) :
$clientCredentialsToken = $oidc->requestClientCredentialsToken()->access_token;
But function requestClientCredentialsToken() doesn't exist in library. Does anyone know how to get token or to recommend some another php library where I can define scope, redirect uri, get client secret and id from open server and offcourse to get token.
Thanks in advance
There is a public function getAccessToken().
You should modify the the code above like this:
$oidc = new OpenIDConnectClient('https://id.provider.com',
'ClientIDHere',
'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');
$oicd->authenticate();
$mytoken=$oidc->getAccessToken();

Bigcommerce customer login api (single sign-on) invalid login issue

I'm new to bigcommerce and jwt tokens. I'm trying to get the customer login api to work on a trail store. But have not been able to successfully login a customer automatically.
I got it to work once or twice, but now it doesn't work anymore, and an unable to figure out the odd behavior since nothing changed with the code. I've tried googling if anyone else has had issues with the customer login api but have found nothing.
I've gone thru the tutorial on https://developer.bigcommerce.com/api/v2/#customer-login-api and copied the example provided.
Is there something I'm missing with the code below?
I've gone to developer.bigcommerce.com and created a draft app.
I got the Client ID and Client Secret from the draft app.
I've gone into my trial store and successfully installed the draft app.
I've tested this page on SSL as well.
Could it be because it's a trail store and it will only work if it's a real store?
Thanks.
Here is the php code below:
include "vendor/autoload.php";
use Bigcommerce\Api\Client as Bigcommerce;
use Firebase\JWT\JWT;
function getCustomerLoginToken($id, $redirectUrl = '', $requestIp = '') {
/*
if (empty(self::$client_secret)) {
throw new Exception('Cannot sign customer login tokens without a client secret');
}
*/
$payload = array(
'iss' => '#MyApp1's Client ID#',
'iat' => time(),
'jti' => bin2hex(random_bytes(32)),
'operation' => 'customer_login',
'store_hash' => '#Store Hash#',
'customer_id' => $id
);
if (!empty($redirectUrl)) {
$payload['redirect_to'] = $redirectUrl;
}
if (!empty($requestIp)) {
$payload['request_ip'] = $requestIp;
}
return JWT::encode($payload, "#MyApp1's Client Secret#", "HS256");
}
$jwt = getCustomerLoginToken(1);
header("Location: " . 'https://store-#Store Hash#.mybigcommerce.com/login/token/' . $jwt);
exit();
There are a couple of constraints that can cause errors:
The app must be installed on the store (seems like you're all good here - you can also test with an API token created locally in the store - https://support.bigcommerce.com/articles/Public/Store-API-Accounts/)
The app must have the Login OAuth scope
The JWT URL must be visited within about 30 seconds, or it won't work.
The computer/server that's generating the JWT needs to have a clock that's synchronized, otherwise your IAT value will appear to have been created more than 30 seconds ago or even in the future which will fail.
The URL can only be visited exactly once - if anything runs a GET request against it other than the intended end user's browser, it won't work. For example, if you send the URL in a Slack message, slack will try to preview the link by visiting it and therefore invalidate it.
It's good to double-check that your JWT is valid at https://jwt.io/
BigCommerce support has access to logs which can shed more light on the situation if you've ruled out the above.
Hope this helps!
do not need app client_id and Secret code , you need to api's client_id and secret code

graph api notifications returns empty data

im building a facebook app and i want to notify the user
https://developers.facebook.com/docs/games/notifications
im using facebook php sdk
what i do:
user auths the app and accepts permission
i get the accesstoken like:
$facebook->getAccessToken()
and then i generate a long-time token like:
public function generateLongTimeToken($token){
$long_time_token_req_body = array(
"grant_type"=>"fb_exchange_token",
"client_id"=>$this->facebookOptions["appId"],
"client_secret"=>$this->facebookOptions["secret"],
"fb_exchange_token"=>$token
);
$query = http_build_query($long_time_token_req_body);
$lttreq = file_get_contents("https://graph.facebook.com/oauth/access_token?".$query);
$lttresp = parse_str($lttreq, $output);
if ( array_key_exists("access_token", $output)){
$this->logger->info("Facebook-app: Successfuly generated long_time_token");
return $output["access_token"];
}else {
$this->logger->err("Facebook-app: generating oauth long_time_token failed \n".$lttreq);
return false;
}
}
some later i use this token for background processes to post on the users wall and them all work fine
now i also want to notificate the user like that :
public function notifyUser($message,$facebookClientId,$token){
$appsecret_proof= hash_hmac('sha256', $token, $this->facebookOptions["secret"]);
$req_body = array(
"access_token"=>$token,
"appsecret_proof"=>$appsecret_proof,
"href"=>"/index",
"template"=>$message,
"ref"=>"post"
);
$query = http_build_query($req_body);
$url = "https://graph.facebook.com/".$facebookClientId."/notifications?".$query;
$lttreq = file_get_contents($url);
return $lttreq;
}
but when i try to notify the user i always get empty data back
when i open the url in browser with all parameters facebook returns the same
{
data: [ ]
}
so i have no idea whats going on,when i look on SO i only find about people posting to sites but i want to notify the user itself
thanks for any help
First, from the Facebook docs:
Currently, only apps on Facebook.com can use App Notifications.
Notifications are only surfaced on the desktop version of
Facebook.com.
Also, an App Token is needed, not a User Token.
Btw, file_get_contents is very bad, use CURL for Facebook. May be another reason why it does not work. A basic example of using CURL with the Facebook API: http://www.devils-heaven.com/extended-page-access-tokens-curl/
Additional Info: I recently wrote a blogpost about App Notifications, it is in german but the small code part may be interesting for you: http://blog.limesoda.com/2014/08/app-notifications-facebook-apps/

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

Twitter OAuth (PHP): Need good, basic example to get started

Using Facebook's PHP SDK, I was able to get Facebook login working pretty quickly on my website. They simply set a $user variable that can be accessed very easily.
I've had no such luck trying to get Twitter's OAuth login working... quite frankly, their github material is confusing and useless for someone that's relatively new to PHP and web design, not to mention that many of the unofficial examples I've tried working through are just as confusing or are outdated.
I really need some help getting Twitter login working--I mean just a basic example where I click the login button, I authorize my app, and it redirects to a page where it displays the name of the logged in user.
I really appreciate your help.
EDIT I'm aware of the existence of abraham's twitter oauth but it provides close to no instructions whatsoever to get his stuff working.
this one is the basic example of getting the url for authorization and then fetching the user basic info when once u get back from twitter
<?php
session_start();
//add autoload note:do check your file paths in autoload.php
require "ret/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//this code will run when returned from twiter after authentication
if(isset($_SESSION['oauth_token'])){
$oauth_token=$_SESSION['oauth_token'];unset($_SESSION['oauth_token']);
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
//necessary to get access token other wise u will not have permision to get user info
$params=array("oauth_verifier" => $_GET['oauth_verifier'],"oauth_token"=>$_GET['oauth_token']);
$access_token = $connection->oauth("oauth/access_token", $params);
//now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
$connection = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token['oauth_token'],$access_token['oauth_token_secret']);
$content = $connection->get("account/verify_credentials");
print_r($content);
}
else{
// main startup code
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
//this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" =>'http://dev.crm.alifca.com/twitter/index.php'));
$_SESSION['oauth_token']=$temporary_credentials['oauth_token']; $_SESSION['oauth_token_secret']=$temporary_credentials['oauth_token_secret'];$url = $connection->url("oauth/authorize", array("oauth_token" => $temporary_credentials['oauth_token']));
// REDIRECTING TO THE URL
header('Location: ' . $url);
}
?>
I just tried abraham's twitteroauth from github and it seems to work fine for me. This is what I did
git clone https://github.com/abraham/twitteroauth.git
Upload this into your webhost with domain, say, www.example.com
Go to Twitter Apps and register your application. The changes that you need are (assuming that you will use abraham's twitteroauth example hosted at http://www.example.com/twitteroauth)
a) Application Website will be http://www.example.com/twitteroauth
b) Application type will be browser
c) Callback url is http://www.example.com/twitteroauth/callback.php (Callback.php is included in the git source)
Once you do this, you will get the CONSUMER_KEY and CONSUMER_SECRET which you can update in the config.php from the twitteroauth distribution. Also set the callback to be the same as http://www.example.com/twitteroauth/callback.php
Thats it. If you now navigate to http://www.example.com/twitteroauth, you will get a "Signin with Twitter", that will take you to Twitter , authorize the request and get you back to the index.php page.
EDIT:
Example will not work but do not worry. Follow the above steps and upload to server.
Make sure you rename the file from github repository i.e. config-sample.php->config.php
if you want to see a working sample, find it here
Here are some OAuth 1.0A PHP libraries with examples:
tmhOAuth
Oauth-php
Twitter async
Twitter async provides documentation on how to simply sign in a user as you asked for.
Here is the step by step guide to integrate Twitter OAuth API to Web-application using PHP. Please following tutorial.
http://www.smarttutorials.net/sign-in-with-twitter-oauth-api-using-php/
You need to create Twitter App First By going thorugh following URL
https://apps.twitter.com/
Then you need to provide necessary information for the twitter app. Once your provided all the information and then save it. You will get Twitter application Consumer Key and Consumer secret.
Please download the source file from above link, and just replace TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET and TWITTER_OAUTH_CALLBACK with your Consumer Key (API Key), Consumer Secret (API Secret) and callback URL. Then upload this to your server. Now it will work successfully.
Abraham's Twitteroauth has a working demo here:
https://github.com/abraham/twitteroauth-demo
Following the steps in the demo readme worked for me. In order to run composer on macOS I had to do this after installing it: mv composer.phar /usr/local/bin/composer
IMO the demo could be a lot simpler and should be included in the main twitteroauth repo.
I recently had to post new tweets to Twitter via PHP using V2 of their API but couldn’t find any decent examples online that didn’t use V1 or V1.1. I eventually figured it out using the great package TwitterOAuth.
Install this package via composer require abraham/twitteroauth first (or manually) and visit developer.twitter.com, create a new app to get the credentials needed to use the API (see below). Then you can post a tweet based on the code below.
use Abraham\TwitterOAuth\TwitterOAuth;
// Connect
$connection = new TwitterOAuth($twitterConsumerKey, // Your API key
$twitterConsumerSecret, // Your API secret key
$twitterOauthAccessToken, // From your app created at https://developer.twitter.com/
$twitterOauthAccessTokenSecret); // From your app created at https://developer.twitter.com/
// Set API version to 2
$connection->setApiVersion('2');
// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);
if (isset($response['title']) && $response['title'] == 'Unauthorized') {
// Handle error
} else {
var_dump($response);
/*
object(stdClass)#404 (1) {
["data"]=>
object(stdClass)#397 (2) {
["id"]=>
string(19) "0123456789012345678"
["text"]=>
string(13) "Hello Twitter"
}
}
*/
}

Categories