Skip to content

Instantly share code, notes, and snippets.

@vitor-mariano
Last active September 29, 2015 17:56
Show Gist options
  • Save vitor-mariano/1a5b4ef77b35cbf5d3d8 to your computer and use it in GitHub Desktop.
Save vitor-mariano/1a5b4ef77b35cbf5d3d8 to your computer and use it in GitHub Desktop.

Installing

Through the Composer, you must use the package matheusmariano/tumblr.

Using

use MatheusMariano\Tumblr\Client;
use MatheusMariano\Tumblr\Connector\Auth\ApiKey;
use GuzzleHttp\Exception\ClientException;

$auth = new ApiKey('my-api-key');
$client = new Client($auth);

try {
    $object = $client->get('blog/nutright.tumblr.com/likes', [
        'api_key' => true,
        'limit' => 10
    ]);
} catch (ClientException $e) {
    // Do something.
}

Authentication

Before request any method from API, is necessary to authenticate our client. For this, there are two authentication levels:

  • API key
  • OAuth

The API key level is the simplest one, because it just needs the consumer key given by the Tumblr when registering your application. To use it, you should import the ApiKey class

use MatheusMariano\Tumblr\Connector\Auth\ApiKey;

and then instantiate it with your consumer key.

$auth = new ApiKey('your-consumer-key');

You can use the OAuth level practically the same way, importing the OAuth class

use MatheusMariano\Tumblr\Connector\Auth\OAuth;

and then instantiating it with all the necessary keys.

$auth = new OAuth; // Also accepts ordered parameters.
$auth->consumerKey = '...';
$auth->consumerSecret = '...';
$auth->oauthToken = '...';
$auth->oauthTokenSecret = '...';

OAuth tokens and Authorizer

To get the tokens from an user is a little bit different task, because he needs to be notified and give authorization to your application. Is a proccess that involves a lot of steps, but the Authorizer class turns everything easier. For every used page, you should import the class this way.

use MatheusMariano\Tumblr\Authorizer;

The first step is to send your consumers to the Tumblr with your callback URI. Let's consider it should be https://example.com/auth/tumblr/callback.

$auth = new OAuth;
$auth->consumerKey = '...';
$auth->consumerSecret = '...';

$authorizer = new Authorizer($auth);
$tokens = $authorizer->getTemporaryTokens('https://example.com/auth/tumblr/callback');

If the consumers are accepted, you will receive temporary tokens.

['oauth_token' => '...', 'oauth_token_secret' => '...']

Save these tokens, because they will be used in the next session. Now you need to redirect your user to https://www.tumblr.com/oauth/authorize?oauth_token={$tokens['oauth_token']}. There, he will be able to authorize your application and then will be redirected to the callback URI.

In the https://example.com/auth/tumblr/callback, the step is to send the consumers and the temporary tokens together with GET parameter oauth_verifier received from Tumblr.

$auth = new OAuth;
$auth->consumerKey = '...';
$auth->consumerSecret = '...';
$auth->oauthToken = $oauthToken;
$auth->oauthTokenSecret = $oauthTokenSecret;

$authorizer = new Authorizer($auth);
$tokens = $authorizer->getTokens($oauthVerifier);

If you prefer, you can use the global $_GET to get the oauth_verifier.

$oauthVerifier = $_GET['oauth_verifier'];

If everything runs as plained, you will receive the user definitive tokens.

Client

After configure one of those authenticators, you can import the Client class

use MatheusMariano\Tumblr\Client;

and then instantiate it with the authenticator.

$client = new Client($auth);

Methods

In the version 0.1 of this package, the Client has only 2 very basic methods

  • get
  • post

Is important to follow the Tumblr API to use these methods and your responses correctly.

Example: getting the text posts that has the fruit tag.

$object = $client->get('blog/nutright.tumblr.com/posts/text', [
    'api_key' => true,
    'tag' => 'fruit',
]);

The response will be an stdClass object with all content of response, following the Tumblr API.

$object->total_posts; // int
$object->posts; // array
$object->blog; // stdClass
$object->blog->title; // string

The post method works the same way.

$client->post('blog/nutright.tumblr.com/post', [
    'type' => 'text',
    'tags' => 'fruit, apple, red',
    'title' => 'My new post title',
    'body' => 'My new post body...',
]);

Exceptions

Request methods may receive errors, generaly 401 not authorized and 404 not found. These errors calls exceptions like GuzzleHttp\Exception\ClientException, GuzzleHttp\Exception\ServerException etc., that can be treated with try...catch. See the Guzzle documentation for more information.

try {
    $client->get('blog/nutright.tumblr.com/followers', ['api_key' => true]);
} catch (\GuzzleHttp\Exception\ClientException $e) {
    // Do something
}

Instalando

Através do Composer, você deve utilizar o pacote matheusmariano/tumblr.

Usando

use MatheusMariano\Tumblr\Client;
use MatheusMariano\Tumblr\Connector\Auth\ApiKey;
use GuzzleHttp\Exception\ClientException;

$auth = new ApiKey('my-api-key');
$client = new Client($auth);

try {
    $object = $client->get('blog/nutright.tumblr.com/likes', [
        'api_key' => true,
        'limit' => 10
    ]);
} catch (ClientException $e) {
    // Do something.
}

Autenticação

Antes de requerir qualquer método da API, é necessário autenticar nosso cliente. Para isso há dois níveis de autenticação:

  • API key
  • OAuth

O nível API key é o mais simples, pois necessita apenas da Consumer Key dada pelo Tumblr ao registrar seu aplicativo. Para utilizá-lo, você deve importar a classe ApiKey

use MatheusMariano\Tumblr\Connector\Auth\ApiKey;

e instanciá-la com sua Consumer Key.

$auth = new ApiKey('your-consumer-key');

Você pode utilizar o nível OAuth praticamente da mesma forma, importanto a classe OAuth

use MatheusMariano\Tumblr\Connector\Auth\OAuth;

e instanciando com todas as chaves necessárias.

$auth = new OAuth; // Also accepts ordered parameters.
$auth->consumerKey = '...';
$auth->consumerSecret = '...';
$auth->oauthToken = '...';
$auth->oauthTokenSecret = '...';

OAuth tokens e Authorizer

Conseguir os tokens de um usuário é uma tarefa um pouco diferente, pois ele necessita ser notificado e dar autorização ao seu aplicativo. É um processo que envolve vários passos, mas que a classe Authorizer facilita tudo. Para cada página utilizada, você deve importar a classe desta forma.

use MatheusMariano\Tumblr\Authorizer;

O primeiro passo é enviar seus consumers ao Tumblr junto à sua página de callback, que vamos usar de exemplo https://example.com/auth/tumblr/callback.

$auth = new OAuth;
$auth->consumerKey = '...';
$auth->consumerSecret = '...';

$authorizer = new Authorizer($auth);
$tokens = $authorizer->getTemporaryTokens('https://example.com/auth/tumblr/callback');

Se os consumers forem aceitos, você receberá os tokens temporários no seguinte formato.

['oauth_token' => '...', 'oauth_token_secret' => '...']

Guarde estes tokens, pois serão utilizados na próxima sessão. Agora você precisa redirecionar seu usuário para https://www.tumblr.com/oauth/authorize?oauth_token={$tokens['oauth_token']}. Neste endereço, ele será habilitado a autorizar seu aplicativo e então redirecionado ao endereço de callback.

Na página https://example.com/auth/tumblr/callback, o passo é enviar os consumers e os tokens temporários juntos ao parâmetro GET oauth_verifier recebido do Tumblr.

$auth = new OAuth;
$auth->consumerKey = '...';
$auth->consumerSecret = '...';
$auth->oauthToken = $oauthToken;
$auth->oauthTokenSecret = $oauthTokenSecret;

$authorizer = new Authorizer($auth);
$tokens = $authorizer->getTokens($oauthVerifier);

Se preferir, você pode utilizar a global $_GET para recuperar o oauth_verifier.

$oauthVerifier = $_GET['oauth_verifier'];

Se tudo ocorrer como planejado, você receberá os tokens definitivos do usuário.

Cliente

Depois de configurar um dos autenticadores, você pode importar a classe Client

use MatheusMariano\Tumblr\Client;

e instanciá-la com o autenticador.

$client = new Client($auth);

Métodos

Na versão 0.1 deste pacote, o Client possui apenas 2 métodos muito básicos

  • get
  • post

É importante seguir a API do Tumblr para utilizar os métodos e as respostas de forma correta.

Exemplo: vendo os posts do tipo texto que tenham o marcador fruit.

$object = $client->get('blog/nutright.tumblr.com/posts/text', [
    'api_key' => true,
    'tag' => 'fruit',
]);

A resposta será um objeto stdClass com o que está contido em response, segundo a API do Tumblr.

$object->total_posts; // int
$object->posts; // array
$object->blog; // stdClass
$object->blog->title; // string

O método post funciona da mesma forma.

$client->post('blog/nutright.tumblr.com/post', [
    'type' => 'text',
    'tags' => 'fruit, apple, red',
    'title' => 'My new post title',
    'body' => 'My new post body...',
]);

Exceções

Métodos de requisição estão sujeitos a erros, geralmente 401 ou 404. Estes erros chamam exceções GuzzleHttp\Exception\ClientException, GuzzleHttp\Exception\ServerException etc., que podem ser tratadas por try...catch. Veja a documentação do Guzzle para mais informações.

try {
    $client->get('blog/nutright.tumblr.com/followers', ['api_key' => true]);
} catch (\GuzzleHttp\Exception\ClientException $e) {
    // Do something
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment