簡體   English   中英

使用Firebase的Twitter API:如何獲取代表用戶發布的twitter accessToken? 我已經成功登錄

[英]Twitter API using Firebase: How do I get the twitter accessToken to post on user's behalf?? I already logged in successfully

我正在使用firebase-UI登錄Twitter,現在,正如文檔所述,我必須使用private void handleTwitterSession(TwitterSession session)方法獲取訪問令牌。 登錄工作正常,但我不知道向該功能發送什么,即所謂的“會話”。 我如何從FirebaseAuth mAuth對象獲取訪問令牌?...非常感謝。 指向文檔的鏈接為https://firebase.google.com/docs/auth/android/twitter-login

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "NearGoal";

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    private List<causes> causesList = new ArrayList<>();
    private List<FundItem> fundItemList = new ArrayList<>();
    private RecyclerView rv;
    private RecyclerView rvgoal;
    private causes_adaptor cAdapter;
    private causes_adaptor_near_goal gAdapter;
    private ProgressBar pb;
    private ProgressBar progressBarGral;
    private Context mContext;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mAuth = FirebaseAuth.getInstance();
         if (mAuth.getCurrentUser() != null) {
            // already signed in
             FirebaseUser firebaseUser=mAuth.getCurrentUser();
             Log.d("TWITTER_USER_INFO",""+mAuth.getCurrentUser().getToken(true));
        } else {
            startActivityForResult(
                    AuthUI.getInstance()
                            .createSignInIntentBuilder()
                            .setProviders(Arrays.asList(
                                     new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
                            .build(),
                    RC_SIGN_IN);
        }
//TwitterAuthProvider
        Fresco.initialize(getApplication());

        setContentView(R.layout.activity_main);

        rv = (RecyclerView) findViewById(R.id.rv);
        rvgoal = (RecyclerView) findViewById(R.id.rvgoal);


        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        rv.setLayoutManager(mLayoutManager);
        rv.setItemAnimator(new DefaultItemAnimator());

        RecyclerView.LayoutManager gLayoutManager =new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvgoal.setLayoutManager(gLayoutManager);
        rvgoal.setDrawingCacheEnabled(true);
        rvgoal.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        rvgoal.setItemAnimator(new DefaultItemAnimator());


        toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        toolbar.setTitle("Your Title");
        //toolbar.setTitleTextColor(getResources().getColor(android.R.color.transparent));

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);


        //tabLayout = (TabLayout) findViewById(R.id.tabs);
        //tabLayout.setupWithViewPager(viewPager);
        //collapsingToolbarLayout.setTitle(" ");


        pb=(ProgressBar) findViewById(R.id.ProgressBar);

        progressBarGral = (ProgressBar) findViewById(R.id.progress_bar);

       // String url = "http://10.0.2.2:3000/api/campaigns/get/all//api/campaigns/get/all/";
        new DownloadTask().execute();;

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
            }
        };

    }
    public class DownloadTask extends AsyncTask<String, Void, Integer> {

        URL url = null;

        @Override
        protected void onPreExecute() {
            progressBarGral.setVisibility(View.VISIBLE);
        }
        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            HttpURLConnection urlConnection;
            try {
                url = new URL(getResources().getString(R.string.backend_base_url)+"/api/campaigns/get/all/");
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }
                    parseResult(response.toString());
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed to fetch data!";
                }
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }
        @Override
        protected void onPostExecute(Integer result) {
            progressBarGral.setVisibility(View.GONE);

            if (result == 1) {
                gAdapter = new causes_adaptor_near_goal(MainActivity.this, causesList);
                //gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
                rvgoal.setAdapter(gAdapter);

                cAdapter = new causes_adaptor(MainActivity.this, causesList);
                //gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
                rv.setAdapter(cAdapter);
            } else {
                Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
            }
        }
        private void parseResult(String result) {
            try {
                JSONObject response = new JSONObject(result);
                JSONArray posts = response.getJSONArray("rows");
                causesList = new ArrayList<>();

                JSONArray funds;

                for (int i = 0; i < posts.length(); i++) {
                    fundItemList = new ArrayList<>();
                   JSONObject post = posts.optJSONObject(i);
                    funds = post.getJSONArray("foundations");

                   causes item = new causes();
                   item.setName(post.optString("name"));
                   item.setcause_description(post.optString("cause_description"));
                   item.setGoal(post.optString("goal"));
                   item.setCurrent_contributions(post.optString("current_contributions"));
                   item.setTotalUniqueUsersReached(post.optString("totalUniqueUsersReached"));
                   item.setState(post.optString("state"));
                   item.setId(post.optString("_id"));
                   item.setRemaining_ammount_to_goal(post.optString("remaining_ammount_to_goal"));
                   item.setGoal_percentage_achieved(post.optString("goal_percentage_achieved"));
                   item.setCampaign_ending_date(post.optString("campaign_ending_date"));




                    for(int k=0, len=funds.length(); k <len;k++) {
                    FundItem fundItem = new FundItem();
                    JSONObject fund = funds.optJSONObject(k);

                        fundItem.setTwitter_account(fund.getString("twitter_account"));
                        fundItem.setName(fund.getString("name"));
                        fundItem.setPic_path(fund.getString("pic_path"));

                    fundItemList.add(fundItem);
                    }
                        item.setFundlist(fundItemList);
                    causesList.add(item);
            }
            } catch (JSONException e) {
                e.printStackTrace();
            }
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // user is signed in!
            Log.d("user_status","user signed in!!");
            return;
        }

        // Sign in canceled
        if (resultCode == RESULT_CANCELED) {
           /* startActivityForResult(
                    AuthUI.getInstance()
                            .createSignInIntentBuilder()
                            .setProviders(Arrays.asList(
                                    new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
                            .build(),
                    RC_SIGN_IN);*/
            return;
        }

        // User is not signed in. Maybe just wait for the user to press
        // "sign in" again, or show a message.
    }


    private void handleTwitterSession(TwitterSession session) {
        Log.d(TAG, "handleTwitterSession:" + session);

        AuthCredential credential = TwitterAuthProvider.getCredential(
                session.getAuthToken().token,
                session.getAuthToken().secret);

        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(getApplicationContext(), "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }



    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }




 }

您可以使用setCallBack()獲取TwitterSession

mLoginButton.setCallback(new Callback<TwitterSession>() {
    @Override
    public void success(Result<TwitterSession> result) {
        Log.d(TAG, "twitterLogin:success" + result);
        handleTwitterSession(result.data);
    }

    @Override
    public void failure(TwitterException exception) {
        Log.w(TAG, "twitterLogin:failure", exception);
    }
});

也看看這個問題。

我通過使用firebase ui onActivityResult參數數據解決了此問題,而不是嘗試使用該handleTwitterSession函數,這是因為firebase-ui已經處理了loginWithCredentials,因此將是多余的。我發布了工作代碼以供將來參考:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) {
            IdpResponse response = IdpResponse.fromResultIntent(data);
            //twitter token
            response.getIdpToken();
            //twitter secret
            response.getIdpSecret();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM