Coder Social home page Coder Social logo

sdk-php's Introduction

OAuth.io PHP SDK

OAuth that just works !

This SDK allows you to use OAuth.io from a PHP backend, to handle the authentication and API calls from your server instead of from your front-end, for 100+ API providers.

The current version of the SDK is 0.3.2. Older versions are deprecated.

You can also get nightlies by checking out our develop branch.

To get more information about this SDK and its method, please refer to its reference documentation on OAuth.io.

Features

  • Server-side OAuth authentication flow
  • Requests to API from the backend
  • Unified user information (.me() method) requests when available
  • Access token renewal with the refresh_token when available

Common use-Case

You don't want to use APIs directly from the front-end, but rather through web-services inside your PHP backend.

Installation

First of all, you'll need to set your app's backend to PHP in your OAuth.io dashboard.

This allows you to get a refresh token from the provider if available.

You can install it through Composer by adding the following dependency to your composer.json :

 "require": {
        ...
        "oauth-io/oauth": "0.3.0"
        ...
    },

Then run in the console :

$ composer install

Using the SDK

The OAuth class is stored in the OAuth_io namespace. You need to include it in your file like this (make sure you have required the Composer autoloader file):

<?php

require_once '/path/to/autoload.php';

use OAuth_io\OAuth;

//?>

PSR-0 support

If you're using Composer with an autoloader, you can use the PSR-0 notation to use this package. Just put the following code at the top of your script :

<?php

use OAuth_io\OAuth;

//?>

Initialization

To initialize the SDK, you have to give it your OAuth.io's app's key and secret (you can grab them on the oauth.io Key-Manager) :

<?php
$oauth = new OAuth();
$oauth->initialize('your_key', 'your_secret');
//?>

Note on session

You can give your own managed session array to the constructor so that if you already have a session manager, the SDK doesn't mess around with it :

<?php
$_SESSION['some_subarray_in_the_session'] = array();
$myarray = $_SESSION['some_subarray_in_the_session'];

$oauth = new OAuth($myarray);
//?>

Note on certificates

If you're using oauthd (the open source version of oauth.io) and that you don't have a verified ssl certificate yet (you should in the future if you want to put your code in production), you can disable the SSL certificate verification like this :

<?php
$oauth = new OAuth(null, false);
//?>

Authenticating the user

The first thing you need to do is to create an endpoint that will redirect your user to the provider's authentication page, so that the user can accept the permissions your app needs.

In this endpoint, call the redirect method like this:

$oauth->redirect('the_provider', '/callback/url');

This will automatically redirect your user to the provider's website. Once he has accepted the permissions, he will be redirected to the '/callback/url' on your app, where you'll be able to retrieve a request object.

In an endpoint associated to the '/callback/url', call the auth method with the redirect option set to true to get a request object, like this:

$request_object = $oauth->auth('the_provider', array(
    'redirect' => true
));

$request_object is an object that allows you to perform requests (see further down to learn how to), and that contains the user's credentials.

Using the session to get a request object

Usually, you'll want to make calls to the API several times while the user is connected to your app. Once you've authenticated the user once with a code, the session is automatically configured to work with the SDK.

Thus, you just need to do this to get a request object:

$request_object = $oauth->auth('the_provider');

Saving credentials to re-generate a request object

You can also save the user's credentials to make requests in a cron. You can get the credentials array from a request object like this :

$credentials = $request_object->getCredentials();
// Here save the $credentials array for later use

Then, when you want to reuse these credentials, you can rebuild a $request_object from them:

$request_object = $oauth->auth('the_provider', array(
    'credentials' => $credentials
));

Making requests to the API

Once you have a request object, you can make requests to the API.

<?php
$response_GET = $request_object->get('https://theprovider.com/api/endpoint');

$response_POST = $request_object->post('https://theprovider.com/api/endpoint', array('some' => 'data'));
$response_PUT = $request_object->put('https://theprovider.com/api/endpoint', array('some' => 'data'));
$response_DELETE = $request_object->del('https://theprovider.com/api/endpoint');
$response_PATCH = $request_object->patch('https://theprovider.com/api/endpoint', array('some' => 'data'));
//?>

You can also call the me(array $filters) method from that request object. This method returns a unified array containing information about the user.

<?php
$facebook_requester = $oauth->auth('facebook', array(
    'redirect' => true
));

$result = $facebook_requester->me(array('firstname', 'lastname', 'email'));

// you'll have $result["firstname"], $result["lastname"] and $result["email"] set with the user's facebook information.
//?>

You can refer to the OAuth.io me() feature to get more information about the fields that are returned by this method.

Refreshing the token

If a refresh token is available and the access token is expired, the auth method will automatically use that refresh token to get a new access token.

You can force the renewal by passing the force_refresh field in the options array:

$request_object = $oauth->auth('the_provider', array(
    'credentials' => $credentials,
    'force_refresh' => true
));

You can also directly refresh a credentials array like this:

$refreshed_credentials = $oauth->refreshCredentials($old_credentials);

Contributing to this SDK

Issues

Please discuss issues and features on Github Issues. We'll be happy to answer to your questions and improve the SDK based on your feedback.

Pull requests

You are welcome to fork and make pull requests. We appreciate the time you spend working on this project and we will be happy to review your code and merge it if it brings nice improvements :)

If you want to do a pull request, please mind these simple rules :

  • One feature per pull request
  • Write clear commit messages
  • Unit test your feature : if it's a bug fix for example, write a test that proves the bug exists and that your fix resolves it.
  • Write a clear description of the pull request

If you do so, we'll be able to merge your pull request more quickly :)

The SDK is written as a Composer module. You can install its dependencies like this :

sdk/folder$ composer install

Testing the SDK

We use PHPUnit to test the SDK. To test it, just run the following from the SDK root folder :

$ ./vendor/phpunit/phpunit/phpunit

License

The SDK is released under the Apache2 license.

sdk-php's People

Contributors

william26 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdk-php's Issues

Facebook email

The unified method: $request_object->me() for facebook does not return the users primary email.

Is there another way to get the facebook email alongwith the basic_profile | aka is there a way to add permission scope

Twitch authentication error

We are trying to write an authantication module for our Drupal 8 website. We are using oAuth.io for external authantications (with social media platforms) every other platform works perfectly. But when we try to login with Twitch we get the error:

Notice: Trying to get property of non-object in OAuth_io\RequestObject->me() (line 133 of [root]/vendor/oauth-io/oauth/src/OAuth_io/RequestObject.php)

This is the code in our redirect page:

$oauth = new OAuth();
        $oauth->initialize(['oauthApiKey'], ['oauthSecretKey']);
        $request_object = $oauth->auth($provider, [
          'redirect' => true
        ]);
 $socialDataArray = $request_object->me('email'); [or ->me() -both the same]

This is very urgent. Could you please help?

Google authentication error 400

Google authentication popup throws this error:

  1. That’s an error.

Error: invalid_request

Missing required parameter: scope

Request Details
response_type=code
access_type=online
redirect_uri=https://oauth.io/auth
state=1UGF0qnuONPgnZDeSK7oT4hl348
client_id=553071262209-g066a765h33jv3tp79ov88c9l0lsmd3l.apps.googleuserconten

Is there any way to send scope in the initial authorization request - this is a similar issue to the Facebook one I posted earlier.

custom value for state variable?

Hi, I love the complete oauth solution provided with oauth.io, oauthd and the various libraries. For a specific application I require the ability to have a custom value for "state" in the json payload. Now it contains a random string generated by this method:
public function generateStateToken()
Would it be an idea to add the ability to customise this somehow? Of course I can easily extend the class myself but I can imagine others could use this functionality as well?

'Class 'Unirest' not found'

I'm using the PHP-SDK of oauth.io. I get the following error:

[2015-02-04 11:35:35] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Unirest' not found' in /home/vagrant/Code/shelfflip-web/vendor/oauth-io/oauth/src/OAuth_io/HttpWrapper.php:33
Stack trace:
#0 [internal function]: Illuminate\Exception\Handler->handleShutdown()

this is my composer file:

"require": {
        "laravel/framework": "4.2.*",
        "mashape/unirest-php": "dev-master",
        "oauth-io/oauth": "0.3.0"
    },

Installation fails

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for oauth-io/oauth 0.2.0 -> satisfiable by oauth-io/oauth[0.2.0].
    - oauth-io/oauth 0.2.0 requires mashape/unirest-php dev-master -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

retrieving refresh_token from google

I have integrated the phonegap sdk and the php server sdk in my application.

I have managed to get to the point, where I can call the me() method of the request_object.
I would like to retrieve to refresh_token, but I can't find a way to do that. What's the supposed way to do that in PHP?

$request_object = $this->oauth->auth('google');
$me = $request_object->me();
Log::debug($me);

On callback URL no JSON field "code" is being returned

After the redirect at this step:

´´´
$request_object = $oauth->auth('the_provider', array(
'redirect' => true
));
´´´

I get error messages and in investigations I traced the problem to src/OAuth_io/OAuth.php line 148:

$code = $data['data']['code'];

When I dump the parsed JSON there is no field code, but there is access_token. Did the returned encoded JSON change? I also tried just setting $code to access_token to verify, but ran into other complications, so I am asking the maintainers here for more informed input.

Wrong Access Token API Endpoint

File: src/OAuth_io/OAuth.php

'url' => $this->injector->config['oauthd_url'] . '/auth/access_token',
should be
'url' => $this->injector->config['oauthd_url'] . '/access_token',

as defined in oauthd here

server.post(config.base + '/access_token', function(req, res, next) {

Getting "Invalid format" error during server side auth

Hi, I have a javascript client and a laravel backend. I successfully got state token by calling generateStateToken() method, but then I send that to $this->oauth->auth() method I get Invalid Format error. Can you please tell me what this error means and what I am doing wrong.

Client Side

var selectedAuth = 'facebook';
$.post('http://localhost/auth/v1/social', {provider: selectedAuth, get_state_token: 1}, function(data){
    OAuth.popup(selectedAuth)
    .done(function(result) {
        console.log(result);
        $.post('http://localhost/auth/v1/social', {provider: selectedAuth, code: data.token, access_token: result.access_token}, function(data){
            console.log(data);
        }, 'json');
    })
    .fail(function (err) {
        //handle error with err
    });
}, 'json');

Server Side

// get state token
$token = $this->oauth->generateStateToken();
return response()->json(['status' => 'success', 'token' => $token]);

--- snip ---

// get access token from state token
$provider = 'facebook';
$request_object = $this->oauth->auth($provider, array(
     'code' => $code
 ));
$credentials = $request_object->getCredentials();

I have verified that $code does have the exact state token that I have received on the 1st step.
The value of $credentials is as follows:

{"status":"error","data":{"code":"Invalid format"},"refreshed":false} 

Please help me out here. This error occurs for twitter auth as well.

Rewrite

After inspecting the architecture of this module I feel a rewrite is in order. I've begun this work here: https://github.com/TomHAnderson/sdk-php/tree/rewrite

The client isn't unit tested or functionally tested but the general shape of the class is coming into view. Rather than an injector pattern this rewrite uses a factory pattern with getters and setters for all options so if what you get from the factory isn't what you need you can set all configurable options manually with setters.

One change stood out in particular: The session use would namespace the app into a [oauthio] namespace. But the code was coded to have an already-namespaced namespace in the session you pass to the client, so all references to this session namespace have been removed. For the sake of a default $_SESSION $_SESSION['oauthio'] is used.

In this rewrite I'll substitute Guzzle for unirest. I'll follow the patterns in the excellent KeenLabs client https://github.com/keenlabs/KeenClient-PHP

I've created this ticket as a forum to bring ideas about a rewrite together and work out the issues between the current and rewrite.

me endpoint

the me endpoint still doesn't work for me... how do i get this to use the data provided in the me.js files. i've found out that this file is returned when i do the following request but i can't find anything else that uses it.

https://domain.com:6284/api/providers/:provider/user-mapping

i've tried both of the available methods:

$req->get('/me')
$req->me()

i also don't think the me.js files are completely accurate.

Missing origin or referer.

This is the auth method in src/OAuth_io/OAuth.php. The screenshot is the relevant section of code from the oauthd server. Any help would be greatly appreciated!

screen shot 2014-07-30 at 12 14 17 pm

AUTH - RESPONSE PRINT_R = Unirest\HttpResponse Object( [code:Unirest\HttpResponse:private] => 400 [raw_body:Unirest\HttpResponse:private] => Missing origin or referer. code: InvalidHeader message: Missing origin or referer. [body:Unirest\HttpResponse:private] => Missing origin or referer. code: InvalidHeader message: Missing origin or referer. [headers:Unirest\HttpResponse:private] => Array ( [Content-Type] => text/html; charset=utf-8 [Content-Length] => 157 [Date] => Wed, 30 Jul 2014 15:31:19 GMT [Connection] => keep-alive ))

No longer working due to Unirest changes

Due to the fact that the composer file has mashape/unirest-php pointing to dev-master rather than a specific release, and also the fact that the sdk is not compatible with the 2.0 version of unirest; the sdk no longer works.

I will attempt to fix and send a PR

syntax error in website example

Not sure where to submit a bug report for your website's examples, so im submitting here

url: https://oauth.io/getting-started?php#ii-using-the-php-sdk-auth-the-user

first php code block reads:

$request_object = $oauth->auth('the_provider', array(
    'code': $code
));

however php array key value pairs are separated with "=>" and javascript is separated with ":" so it should read

$request_object = $oauth->auth('the_provider', array(
    'code' => $code
));

(the same example is in dashboard>try auth)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.