I am working on a PHP app in which I need to use Dropbox web service. The requirement is that when user clicks on 'Integrate with Dropbox' link, Dropbox login popup should be shown and after successful login, it should show an other popup in which user can select Dropbox folder. Then when user uploads file from my custom PHP app, that file should get stored in selected Dropbox folder.
In all this process, user should not be redirected away from my custom PHP app.
How can I achieve this?
Do I need to create login popup for dropbox, or drop box provides one?
I believe you can find all the info about logging a user and uploading data here:
Dropbox - Using the Core API in PHP
As you can see you should create an app, get an access token (trough OAuth2 flow) and use this one to make API requests on behalf of the user. If you need to keep your user on your site you can involve Ajax to build a structure to make the calls for login, authorization, etc..
Basically these are the steps:
// Include Dropbox PHP Sdk and create a new AuthBase instance (WebAuthNoRedirect is a subclass of).
$dropboxAppAuth = new dbx\WebAuth($yourAppInfo, "examples-authorize", new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token'););
// Get an authorize url
$authorizeUrl = $dropboxAppAuth->start();
// Invite the user to authorize your app via this url
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
...
// and get an access token from the GET array.
list($accessToken, $userId, $urlState) = $webAuth->finish($_GET);
// Now you need a Client instance to make you call using the API interface
$dropboxClient = new dbx\Client($accessToken, "examples-authorize");
$accountInfo = $dropboxClient->getAccountInfo();
// Get a file pointer resource from the resource you want to upload and send it using the `uploadFile()` method from the Dropbox API
$resourceFilename = 'my-data.txt';
$f = fopen($resourceFilename, "rb");
$result = $dropboxClient->uploadFile("/".$resourceFilename, dbx\WriteMode::add(), $f);
However at the end of that page you can find this basic example, complete and ready to start to play with it.
Did you research the Dropbox API?
https://www.dropbox.com/developers/dropins/saver
You can't do it using PHP alone, you need AJAX to save data to Dropbox.
Related
I am currently new to using php and Laravel and working with an API however I have been following the Spotify PHP tutorial https://github.com/jwilsson/spotify-web-api-php.
I've also put in bold some of my questions that I wanted to ask , hopefully someone can help.
I have followed all steps but need help just to get it working.
Put the following code in its own file, lets call it auth.php. Replace CLIENT_ID and CLIENT_SECRET with the values given to you by Spotify.
(Where abouts should I save this file?)
The REDIRECT_URI is the one you entered when creating the Spotify app, make sure it's an exact match.
(I used my localhost:8888/callback/ not sure if that is correct?) Obviously I haven't put me details in here on this website as for security reasons.
<?php
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ ID',
'CLIENT_SECRET',
'REDIRECT_URL'
);
$options = [
'scope' => [
'playlist-read-private',
'user-read-private',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
?>
When the user has approved your app, Spotify will redirect the user together with a code to the specifed redirect URI. You'll need to use this code to request a access token from Spotify.
put this code in a new file called callback.php:
Do replace client id and secret with my detail? also how do I save the access token?
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'REDIRECT_URI'
);
// Request a access token using the code from Spotify
$session->requestAccessToken($_GET['code']);
$accessToken = $session->getAccessToken();
$refreshToken = $session->getRefreshToken();
// Store the access and refresh tokens somewhere. In a database for example.
// Send the user along and fetch some data!
header('Location: app.php');
die();
In a third file, app.php, tell the API wrapper which access token to use, and then make some API calls!
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
require 'vendor/autoload.php';
$api = new SpotifyWebAPI\SpotifyWebAPI();
// Fetch the saved access token from somewhere. A database for example.
$api->setAccessToken($accessToken);
// It's now possible to request data about the currently authenticated user
print_r(
$api->me()
);
// Getting Spotify catalog data is of course also possible
print_r(
$api->getTrack('7EjyzZcbLxW7PaaLua9Ksb')
);
(Where abouts should I save this file?)
You can save this file in differents places in laravel, for testing you could write it in a controller (not the best but you can).
Do replace client id and secret with my detail?
Yes of course !
also how do I save the access token?
You can save in a database or in a session or where you want. If you store it in a session you will have to make a new request to get a new Access token if the user logged out of your application. In a database you can reuse it.
Many access token are only available for a specific duration. The spotify doc should speak of it.
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
For testing you can do this in your controller, but it's a good idea to have a service layer where you put the business logic of your application.
Do not copy require 'vendor/autoload.php'; in your file laravel handle the composer autoload already.
I am using a simple php script which generates a task's name (it is quite long, that's why I build a generator for generating it).
Right now I need to copy generated name to ASANA, while I am creating a new task but I know that using ASANA API it can be integrated with my generator (when I click on GENERATE button the project's name is generated and a new ASANA task has been created with the generated name).
I created in my dashboard a Personal access token.
I downloaded this library https://github.com/ajimix/asana-api-php-class and filled up file examples/task-creation.php (all 3 fields with capital letters are correct filled):
<?php
require_once('../asana.php');
// See class comments and Asana API for full info
$asana = new Asana(array('personalAccessToken' => 'MY PERSONAL ACCESS TOKEN')); // Create a personal access token in Asana or use OAuth
$workspaceId = 'MY WORKSPACE ID'; // The workspace where we want to create our task, take a look at getWorkspaces() method.
// First we create the task
$asana->createTask(array(
'workspace' => $workspaceId, // Workspace ID
'name' => 'Hello World!', // Name of task
'assignee' => 'HERE MY EMAIL' // Assign task to...
));
// As Asana API documentation says, when a task is created, 201 response code is sent back so...
if ($asana->hasError()) {
echo 'Error while trying to connect to Asana, response code: ' . $asana->responseCode;
return;
}
$result = $asana->getData();
if (isset($result->id)) {
echo $result->id; // Here we have the id of the task that have been created
}
?>
After running the script from my localhost directory I get following error:
Error while trying to connect to Asana, response code: 0
Any help regarding this problem will be appreciated.
Please move your file to an online host instead of localhost. It should work.
I am attempting to allow a user add items to the calendars of other users.
A user logs in and get the token as follows
const AUTHORIZE_ENDPOINT = '/oauth2/v2.0/authorize';
const TOKEN_ENDPOINT = '/oauth2/v2.0/token';
const SCOPES = 'profile openid email User.Read Calendars.ReadWrite Calendars.Read Calendars.Read.Shared Calendars.ReadWrite Calendars.ReadWrite.Shared';
$graph = new Graph();
$graph->setAccessToken($token);
$response = $graph->createRequest("GET", "/me")->setReturnType(Model\User::class)->execute();
The logged in user can add to their own calendar using
$request = $graph->createRequest("post", '/me/events');
$request->attachBody($data);
$response = $request->execute();
But, when I try to add to another user with
$request = $graph->createRequest("post", '/anotheruser/events');
$request->attachBody($data);
$response = $request->execute();
I get the message
Resource not found for the segment
Have done the admin auth consent, so all should be fine.
Any suggestions?
If you want to access another user's data you have to use the following url:
/users/{id | userPrincipalName}
Your request was just in the wrong form and you ended up sending a request to an non existing resource, thus Graph didn't know what to do.
In your case you just need to prepend /users (for more information see documentation).
So your request could look like this:
$request = $graph->createRequest("post", '/users/anotheruser/events');
Keep in mind that if you are logged in as a user (token on behalf of a user), the calendar you try to access to must have been shared with the logged in user. Otherwise it will fail due to missing privileges as Graph only allows to edit Calendars that are shared with the user. You also need the Permissions Calendars.Read.Shared and/or Calendars.ReadWrite.Shared (which you seem to already have aquired).
Calendar sharing is unnecessary if you gain access without a user as you then automatically have full access to all users.
Currently the Graph API only supports access to shared Calendars but no operations to edit/change the sharing status or see which Calendars are shared with a user. However you can change the sharing status manually over outlook or the powershell.
Url should be something like Users('anotheruser')/events. Since you are directly saying anotheruser/events. The service is not recognizing another user as a valid segment and throwing the error.
I'm trying to call a very simple google apps script from php using a service account so that only my server can access it, not users of the website.
Here is how I do. I create the script here https://script.google.com
function get() {
return ContentService.createTextOutput('get method');
}
and a new project is automatically associated when i save it.
Then I open File > Project Properties to get the scriptId = MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt
I access the developer console of the associated project threw Resources > Project Developers console by clicking on the project link at the top of the popup displayed.
Then I click 'Activate and manage API' and activate the 'Google Apps Script Execution API'. I click on 'Credentials' and see that the previous operation automatically created OAuth2 credentials. But what I need is service account credentials. Then I create one Add credentials > Service account and download generated p12 file. I get the clientId = 109160023321840004240 and clientMail = account-1#project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com for this service account.
I go back to my script and share it with the service account email with read&write access File > Share. First of all i get an email in my personal mailbox which notifies me that
Delivery to the following recipient failed permanently:
account-1#project-id-uokwrcpiqeewhwvpdhb.iam.gserviceaccount.com
Then I publish the script as an execution API Publish > Publish as an execution API with access to everybody.
Now lets go on the PHP server side. Using the 'Google APIs Client Library for PHP' available here https://github.com/google/google-api-php-client I try to call my script function from PHP:
$client = new Google_Client();
$client->setClientId('109160023321840004240');
$client->setApplicationName('myScript');
$cred = new Google_Auth_AssertionCredentials(
'account-1#project-id-okwrcpiqeewhwvpdhb.iam.gserviceaccount.com',
[/*no scope nedeed for this simple script*/],
file_get_contents('path_to_myScript.p12')
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Script($client);
$scriptId = 'MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt';
// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction('get');
$response = $service->scripts->run($scriptId, $request);
And here is the response I get all the time
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (403) The caller does not have permission
If, when I deploy the script, I choose to give access to 'Me only', i get the following response.
Error calling POST https://script.googleapis.com/v1/scripts/MM8zQqofS1OIcnFiNSlm1CGEl5qMrMVBt:run: (404) Requested entity was not found.
I would be so happy if one of you have an idea to help me :)
apps script does not yet support service accounts with execution api. see https://code.google.com/p/google-apps-script-issues/issues/detail?id=5461
google said they are looking into it but apparently wont happen soon (based on google replies on google+ posts about this like https://plus.google.com/+MartinHawksey/posts/Zquix9XqzkK)
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"
}
}
*/
}