8

Sto sviluppando un'applicazione per Android. Con l'imminente deprecazione dell'autorizzazione offline_access di Facebook, sto cercando di utilizzare l'API Graph per estendere il token di Facebook.Qual è il codice per ottenere un token Facebook aggiornato in un'app Android?

 https://graph.facebook.com/oauth/access_token?    
     client_id=APP_ID& 
     client_secret=APP_SECRET& 
     grant_type=fb_exchange_token& 
     fb_exchange_token=EXISTING_ACCESS_TOKEN 

Qualcuno può fornire il codice dettagliato che illustra come implementare il codice sopra in un app Android e ottenere il rinfrescato Facebook gettone?

Grazie per il vostro tempo.

aggiornare due:

Progress (credo)!

Utilizzando l'URL completo con il metodo di richiesta facebook comporta l'URL di base viene aggiunto al all'inizio del URL Così, invece di

String refreshUrl = "https://graph.facebook.com/oauth/access_token?client_id=12345678910&client_secret=abcdefghijklmnopqrstuvwxyz&grant_type=fb_exchange_token&fb_exchange_token="+currentAccessToken; 

dovrebbe usare

String refreshUrl = "oauth/access_token?client_id=12345678910&client_secret=abcdefghijklmnopqrstuvwxyz&grant_type=fb_exchange_token&fb_exchange_token="+currentAccessToken; 

Comunque sono ora ricevendo la risposta {"errore": {"messaggio": "Errore di convalida dell'applicazione. ID applicazione non valido.", "tipo": "OAuthException", "codice": 190}}

Aggiornamento uno:

Ecco cosa ho provato. Il codice viene completato, ovvero OnComplete sul lister viene chiamato, MA la risposta non contiene un nuovo token di accesso o un valore di scadenza.

void refreshWithGraph() { 
     AsyncFacebookRunner extendingAsyncRunner = new AsyncFacebookRunner(facebook); 
     Bundle parameters = new Bundle(); 

     //the variable currentAccessToken is obtained after authorisation is complete using currentAccessToken = facebook.getAccessToken(); 

     String refreshUrl = "https://graph.facebook.com/oauth/access_token?client_id=12345678910&client_secret=abcdefghijklmnopqrstuvwxyz&grant_type=fb_exchange_token&fb_exchange_token="+currentAccessToken; 


    extendingAsyncRunner.request(refreshUrl, parameters, new RefreshListener(), null); 
    } 

Ecco la mia versione di RefreshListener ...

//REFRESH LISTENER 
    public class RefreshListener extends BaseRequestListener { 

     public void onComplete(final String response, Object state) { 


      try { 
       final JSONObject json = Util.parseJson(response); 

       runOnUiThread(new Runnable() { 

        @Override 
        public void run() {    
         tvRefreshResponse.setText("IN REFRESH LISTENER ONCOMPLETE\nResponse is " + response); 
         tvRefreshToken.setText("IN REFRESH LISTENER ONCOMPLETE\nToken is " + facebook.getAccessToken()); 
         tvRefreshExpiry.setText("IN REFRESH LISTENER ONCOMPLETE\nFacebook expiry is " + millisecToDate(facebook.getAccessExpires())); 

        } 

       }); //end runOnUiThread 



      } catch (JSONException e) { 
       runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           tvRefreshResponse.setText("IN REFRESH LISTENER ONCOMPLETE CAUGHT JSON EXCEPTION \nResponse is " + response); 

          } 

         }); //end runOnUiThread 

      } catch (FacebookError fe) { 
       runOnUiThread(new Runnable() { 


          @Override 
          public void run() { 
           tvRefreshResponse.setText("IN REFRESH LISTENER ONCOMPLETE CAUGHT FACEBOOK ERROR \nResponse is " + response); 

          } 

         }); //end runOnUiThread 
      } //end catch Facebook error 

     } //end onComplete 


     @Override 
     public void onIOException(IOException e, Object state) { 
      tvRefreshResponse.setText("IN REFRESH LISTENER IOEXCEPTION \nException is "+ e.getLocalizedMessage()); 

     } 

     @Override 
     public void onFileNotFoundException(FileNotFoundException e, Object state) { 
      tvRefreshResponse.setText("IN REFRESH LISTENER FILE NOT FOUND EXCEPTION \nException is "+ e.getLocalizedMessage()); 
     } 

     @Override 
     public void onMalformedURLException(MalformedURLException e, Object state) { 
      tvRefreshResponse.setText("IN REFRESH MALFORMED URL \nException is "+ e.getLocalizedMessage()); 

     } 

     @Override 
     public void onFacebookError(FacebookError e, Object state) { 
      tvRefreshResponse.setText("IN REFRESH ONFACEBOOK ERROR \nException is "+ e.getLocalizedMessage()); 

     } 
    } //end RefreshListener 

Il codice completa, cioè OnComplete sul listerner si chiama, ma la risposta non contiene un nuovo accesso valore simbolico o di scadenza. La risposta è ...

{"id":"https:\/\/graph.facebook.com\/oauth\/access_token","shares":78,"comments":1} 

Quando ho messo lo stesso URL (con un valore simbolico corrente alfanumerico) in un browser web la risposta include un token di accesso.


Informazioni relative al

il permesso offline_access di Facebook sarà deprecato il 1 maggio 2012

Si prega di non suggerire utilizzando la funzione extendAccessTokenIfNeeded in onResume(), invece.I am also having trouble con quello ed è la ragione per cui sto cercando in token :-) rinfrescante Graph API

correlati Stack Overflow domande

Is it possible to extend Facebook tokens with extendAccessTokenIfNeeded in an Android app? (la mia domanda)

How would offline_access work after deprecation after May 1st?

Facebook access token can not be extended

Protecting app secret for extendAccessToken usage (Java/Android)

Rilevante Facebook collega

Facebook Android Tutorial

Facebook offline_access permission deprecation

+0

Con tutti i link sopra, perché avete bisogno di informazioni più dettagliate? Sembra che tu abbia abbastanza documentazione per implementare questo .. – Shreeni

+0

Penseresti che potrei risolverlo, ma no. :-(Tutta la facile domanda su Stack Overflow ha una risposta completa molto rapidamente, quindi immagino che non sia così facile come sembra ... – Mel

risposta

7

Per essere onesto, sono un po 'confuso - sembra che avete tutto per farlo fare - ed è semplice . Ma lasciami provare a rispondere alla tua domanda. Ecco il codice dal mio progetto C#, dove va il gettone di app con i miei commenti nel caso in cui non si ha familiarità con C# lingue e classi:

string currentToken = "token from somewhere"; 

// WebClient is used to send GET request to the given URL 
// and receive the response 
using (var req = new System.Net.WebClient()) 
{ 
    // create URL string and fill it in with data (app Id, secret, and current token) 
    var extendTokenUrl = string.Format(
     "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=fb_exchange_token&fb_exchange_token={2}", 
     FB_APP_ID, 
     FB_APP_SECRET, 
     currentToken); 

    // send GET request and download the response 
    var response = req.DownloadString(extendTokenUrl); 

    // if all is good, response will be a string which looks like this: 
    // access_token=<<THE TOKEN GOES HERE>> 
    var newToken = response.Substring("access_token=".Length); 

    // now save newToken in your DB INSTEAD of currentToken - 
    // so all calls will be made with extended token 
    SaveTokenInDB(newToken); 
} 

speranza che aiuta, e tradurre questo in Java dovrebbe essere semplice.

+0

Ciao grazie per la tua risposta Sono confuso me stesso! Quello che mi è stato detto è un compito facile non è ottenere alcuna risposta dagli sviluppatori Android - anche con il bounty di 100 punti! Il mio problema di codifica è che la risposta di Facebook non contiene una chiave di accesso, tuttavia, quando metto l'intero URL in un browser, ottengo una chiave di accesso Ho aggiornato la mia risposta per includere i miei tentativi precedenti – Mel

+0

Ho notato subito che analizzi JSON nel tuo RefreshListener, ma è sbagliato, credo: non stai recuperando JSON ma solo una stringa grezza. si incolla il valore di "String refreshUrl" nel browser, si ottiene il token corretto? Sei sicuro al 100% che stai facendo la richiesta GET (invece di POST)? Inoltre, hai fonti per AsyncFacebookRunner? puoi scoprire DOVE è effettivamente invia una richiesta HTTP e registra l'URL esatto , Metodo HTTP lì? Inoltre, se NON si utilizza AsyncFacebookRunner ma solo il componente di richiesta HTTP standard, funzionerà? – avs099

+0

Grazie, sto facendo progressi ... Quando modifico il codice nel codice Util.java dell'SDK (che è la classe che effettivamente fa la richiesta http), comincio ad ottenere la stessa risposta di quando digito un indirizzo nel browser. Ma ora mi rendo conto che la cifra di scadenza è molto piccola (5143168). Quando aggiorno la cifra diminuisce sempre ... Qualche idea su questo? Esempio di risposta ... access_token = AAAEparERUxABAFSPLEI8VNAwo8FLsxOpR6bZAgyeRxj0JAtGBBqMv5y3gnMkvy0TMCrnKuF0Jp6S1DSpiO8mmiy3JMBV2XZASAimYwZDZD e scade = 5143168 – Mel

Problemi correlati