How to consume 4shared REST API using PHP?

Asked

Viewed 1,349 times

0

I tried every way to use this new 4SHARED API, both with Curl and file_get_contents and cannot authenticate!

4shared has not released any class equal twitter and facebook disponibilza and I’m having difficulty making the request.

Documentation: http://www.4shared.com/developer/docs

In the documentation the method of starting the authentication is POST, so I used the following code:

$service_url = 'api.4shared.com/v1_2/oauth/initiate';
$curl = curl_init($service_url);
$curl_post_data = ''; 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$resposta = curl_exec($curl); 
curl_close($curl);

echo var_dump($resposta); 

//resposta: "message=Unauthorized.&code=400.0300&cause=Some of required parameters (oauth_consumer_key&oauth_signature&oauth_signature_method&oauth_timestamp&oauth‌​_nonce) absent"

Ai when I use Curl, the return is this:

message=Unauthorized. &code=400.0300&cause=Some of required Parameters (oauth_consumer_key&oauth_signature&oauth_signature_method&oauth_timestamp&oauth _nonce) absent.

If use file_get_contents() the return is:

"400 bad request".

4shared provides only "Auth Consumer Key" and "Auth Consumer Key Secret"".

Does anyone have any ideas to help me?

  • Error appears?

  • No... more when I file get Contents from "400 base request error"

  • error 400 is already a start says that has a problem sending the request, maybe in the current form it is not valid.

  • Yes... Ai when I use Curl, the return is this: message=Unauthorized. &code=400.0300&cause=Some of required Parameters (oauth_consumer_key&oauth_signature&oauth_signature_method&oauth_timestamp&oauth _nonce) absent.

  • Edit the question and paste this information :)

  • Okay, I hope someone helps.

  • You can put the variable value $curl_post_data it has the fields sent by the right Curl?

  • yes the problem is that I do not know what to put there... Take a look at the documentation to see if you can understand.

  • Then I’ll take a look, here’s bloqueda kkk

  • Okay, I appreciate your help!

  • Leo, these missing parameters need to be generated and sent together with the request. They are part of the authentication flow via Oauth 1.0. The best is to use a lib client in PHP that does this, you just need to inform the Urls, the key and secret Consumer. I managed to make it work using a lib. I will post a reply.

  • Okay man, I really appreciate you helping me out, I’ve been fighting for this API for days because I use an old one and soon they’ll let it go and I’ll be hurt, so I’m looking to update soon!

Show 7 more comments

1 answer

0


There are parameters that are required for the Oauth 1.0 authentication flow to work properly:

  • oauth_signature
  • oauth_signature_method
  • oauth_timestamp
  • oauth _nonce

Either you fill them all in manually or use a lib client to consume the service.

In the example below I will use a lib and will not reinvent the wheel:

  1. Download the lib (latest version Nov 24, 2010, don’t be scared because Oauth goes in version 2.0 and 4shared uses version 1.0) here: https://code.google.com/archive/p/oauth-php/downloads

  2. Unzip . zip, we will only need the folder library. Search for it and copy to the root of your project.

  3. Now you need to register an APP in 4shared (no need to fill in the field Application domain, this will be done in our script): http://www.4shared.com/developer/docs/app/

  4. After creating the APP, the following data will be provided:

    • Consumer Key
    • Consumer Secret
    • Initiate address
    • Authorize address
    • Request token address

Now we just need to create a script to use lib and consume the service. In the same place where you placed the folder library, created a new file .php with the following content:

<?php
// Adicionar as bibliotecas, se colocar a pasta library em outro diretório, coloque o caminho correto abaixo. No meu caso a pasta está no mesmo diretório que o arquivo .php
include_once "library/OAuthStore.php";
include_once "library/OAuthRequester.php";

define("FOURSHARED_CONSUMER_KEY", "<KEY>");
define("FOURSHARED_CONSUMER_SECRET", "<SECRET>");
define("FOURSHARED_OAUTH_HOST", "https://api.4shared.com");
define("FOURSHARED_REQUEST_TOKEN_URL", FOURSHARED_OAUTH_HOST . "/v1_2/oauth/initiate");
define("FOURSHARED_AUTHORIZE_URL", FOURSHARED_OAUTH_HOST . "/v1_2/oauth/authorize");
define("FOURSHARED_ACCESS_TOKEN_URL", FOURSHARED_OAUTH_HOST . "/v1_2/oauth/token");
define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));

//Coloque aqui a URL do servidor que você utiliza para testes. No meu caso eu configurei um vhost e coloquei o caminho para o próprio script.
define("FOURSHARED_OAUTH_CALLBACK", "http://testes.loc/4shared.php");    

//  Inicia o OAuthStore
$options = array(
    'consumer_key' => FOURSHARED_CONSUMER_KEY, 
    'consumer_secret' => FOURSHARED_CONSUMER_SECRET,
    'server_uri' => FOURSHARED_OAUTH_HOST,
    'request_token_uri' => FOURSHARED_REQUEST_TOKEN_URL,
    'authorize_uri' => FOURSHARED_AUTHORIZE_URL,
    'access_token_uri' => FOURSHARED_ACCESS_TOKEN_URL
);

// Atenção: não armazene os dados em "Session" em produção. 
// Escolha uma base de dados.
OAuthStore::instance("Session", $options);

try
{
    //  Passo 1:  se não existir um OAuth token ainda, precisamos de um.
    if (empty($_GET["oauth_token"]))
    {
        $getAuthTokenParams = array(
            'scope' => FOURSHARED_OAUTH_HOST . '/v1_2',
            'xoauth_displayname' => 'Oauth 4Shared',
            'oauth_callback' => FOURSHARED_OAUTH_CALLBACK
        );

        // Solicita um request token
        $tokenResultParams = OAuthRequester::requestRequestToken(FOURSHARED_CONSUMER_KEY, 0, $getAuthTokenParams);

        // Redireciona para a página de autorização. Aqui o utilizador dará permissões na primeira vez e depois será redirecionado novamente para o seu site.
        header("Location: " . FOURSHARED_AUTHORIZE_URL . "?oauth_token=" . $tokenResultParams['token']);
    }
    else {
        //  Passo 2:  solicitar um access token
        $oauthToken = $_GET["oauth_token"];
        $tokenResultParams = $_GET;

        try {
            OAuthRequester::requestAccessToken(FOURSHARED_CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);
        }
        catch (OAuthException2 $e)
        {
            var_dump($e);
            return;
        }

        // Vamos solicitar informações do utilizador
        $request = new OAuthRequester(FOURSHARED_OAUTH_HOST . '/v1_2/user', 'GET', $tokenResultParams);
        $result = $request->doRequest(0);
        if ($result['code'] == 200) {
            // Converter string para um objeto json
            $user = json_decode($result['body']);

            // Imprimir em tela o e-mail;
            echo $user->email;
        }
        else {
            echo 'Error';
        }
    }
}
catch(OAuthException2 $e) {
    echo "OAuthException:  " . $e->getMessage();
    var_dump($e);
}

Don’t forget to change the values in the above script for constants FOURSHARED_CONSUMER_KEY, FOURSHARED_CONSUMER_SECRET and FOURSHARED_OAUTH_CALLBACK.

You need to improve the script, for example, if you refresh the browser after getting the user’s email, an Oauthexception will occur.

The error occurs because when doing refresh the same token is used to get a new access token. By managing this with a database, you can make a more complex system by storing the user id on your system, the access token and its validity, so before requesting a new access token, you check if for the X user there is still a valid.

Another point is that in the example everything is stored in session and in production must be saved in database, precisely to implement what I wrote above.

You should study a little more authentication via Oauth 1.0. Try to understand the flow that everything will become clearer.

Links:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.