How to consume REST API from 4Shared using PHP?

0

I have tried every way to use this new 4SHARED API, both with curl and file_get_contents and I can not authenticate!

4Shared has not provided any class like twitter and facebook available and I'm having trouble making the request.

Documentation: link

In the documentation the method of initiating 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"

When I use curl, the return is this:

  

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

If file_get_contents () is used, the return is:

"400 bad request".

This information I do not have, 4shared provides only the "Auth Consumer Key" and "Auth Consumer Key Secret".

Does anyone have an idea to help me?

    
asked by anonymous 04.03.2016 / 19:28

1 answer

1

There are parameters that are required for the Oauth 1.0 authentication stream to work correctly:

  • oauth_signature
  • oauth_signature_method
  • oauth_timestamp
  • oauth _nonce

Either you manually populate all or use a lib client to consume the service.

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

  • Download lib (latest version Nov 24, 2010, do not be scared because Oauth goes in version 2.0 and 4shared uses version 1.0) here: link

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

  • Now you need to register an APP on 4Shared (you do not need to fill in the Application domain field, this will be done in our script): link

  • 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 the lib and consume the service. In the same place where you put the library folder, I 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);
    }
    

    Do not forget to change the values in the above script for the 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 retrieving the user's email, an OAuthException will occur.

    The error occurs because doing refresh uses the same token to get a new access token. When 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 for user X there is still a valid.

    Another point is that in the example everything is stored in session and in production it should be stored in the database, just to implement what I wrote above.

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

    Links:

    05.03.2016 / 02:12