How to generate token with bank account in stripe? - android

I integrated stripe in my android project. Now, I am generating token with card in stripe. That is working fine. But, I want to generate token with Bank Account. I searched in StackOverflow referred some of links. But, it doesn't worked for me. Is there is any way to generate stripe token with bank account in android?
The following code I used. But, it not worked.
Stripe.apiKey = "sk_test_...";
Map<String, Object> tokenParams = new HashMap<String, Object>();
Map<String, Object> bank_accountParams = new HashMap<String, Object>();
bank_accountParams.put("country", "US");
bank_accountParams.put("currency", "usd");
bank_accountParams.put("account_holder_name", "Jane Austen");
bank_accountParams.put("account_holder_type", "individual");
bank_accountParams.put("routing_number", "11000000");
bank_accountParams.put("account_number", "000123456789");
tokenParams.put("bank_account", bank_accountParams);
try {
Token s = Token.create(tokenParams);
Log.d("Token",s.getId());
tokens = s.getId();
} catch (AuthenticationException e) {
showAlertMessage("",e.getMessage());
} catch (CardException e) {
showAlertMessage("",e.getMessage());
} catch (APIException e) {
showAlertMessage("",e.getMessage());
} catch (InvalidRequestException e) {
showAlertMessage("", e.getMessage());
} catch (APIConnectionException e) {
showAlertMessage("",e.getMessage());
}

According to the new docs you need to add following line to gradle build:
compile 'com.stripe:stripe-android:4.0.1'
check for the latest version at this link
Then use the following code snippet:
Stripe stripe = new Stripe(this);
stripe.setDefaultPublishableKey("your_publishable_key");
BankAccount bankAccount = new BankAccount("accountNumber","countryCode","currency","routingNumber");
stripe.createBankAccountToken(bankAccount, new TokenCallback() {
#Override
public void onError(Exception error) {
Log.e("Stripe Error",error.getMessage());
}
#Override
public void onSuccess(com.stripe.android.model.Token token) {
Log.e("Bank Token", token.getId());
}
});
This should work like charm.

I made a mistake in my code. That is Token.create(tokenParams); should be handled with in AysncTask. Because it deals with network. After gone through their git repository I came to know. So, I handled that create token part in async task. The code I have changed is below:
int SDK_INT = android.os.Build.VERSION.SDK_INT;
final String[] tokens = {"new"};
Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
final Map<String, Object> tokenParams = new HashMap<String, Object>();
Map<String, Object> bank_accountParams = new HashMap<String, Object>();
bank_accountParams.put("country", "US");
bank_accountParams.put("currency", "usd");
bank_accountParams.put("account_holder_name", "Jayden Moore");
bank_accountParams.put("account_holder_type", "individual");
bank_accountParams.put("routing_number", "110000000");
bank_accountParams.put("account_number", "000123456789");
tokenParams.put("bank_account", bank_accountParams);
final Token[] responseToken = {null};
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
com.stripe.Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
new AsyncTask<Void, Void, Token>() {
String errorMsg = null;
#Override
protected Token doInBackground(Void... params) {
try {
return Token.create(tokenParams);
} catch (AuthenticationException e) {
e.printStackTrace();
return null;
} catch (InvalidRequestException e) {
e.printStackTrace();
return null;
} catch (APIConnectionException e) {
e.printStackTrace();
return null;
} catch (CardException e) {
e.printStackTrace();
return null;
} catch (APIException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Token result) {
if (errorMsg == null) {
// success
} else {
// handleError(errorMsg);
}
}
}.execute();
}

I had the same problem and I fixed it by changing this line
compile 'com.stripe:stripe-android:+
into this line
compile 'com.stripe:stripe-android:1.1.1'
in my app.gradle file.
This might change for future releases.

Related

java.lang.NullPointerException: No authentication header information #467

private void setOauthParameter() {
GoogleOAuthParameters oauthParam = new GoogleOAuthParameters();
oauthParam.setOAuthConsumerKey(ClientId);
oauthParam.setOAuthConsumerSecret(ClientSecrate);
oauthParam.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH);
// Init the service and set the auth
service = new ContactsService("chat.com.contactssharing");
try {
service.setOAuthCredentials(oauthParam, new OAuthHmacSha1Signer());
service.getRequestFactory().setHeader("User-Agent", "chat.com.contactssharing");
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void queryEntries() throws IOException, ServiceException {
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(50);
myQuery.setStartIndex(1);
myQuery.setStringCustomParameter("showdeleted", "false");
myQuery.setStringCustomParameter("requirealldeleted", "false");
myQuery.setStringCustomParameter("sortorder", "ascending");
try {
// Execution of this line i'm getting an exception
ContactFeed resultFeed = (ContactFeed) this.service.query(myQuery, ContactFeed.class);
Log.d(TAG, resultFeed.toString());
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
}
System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");
} catch (Exception ex) {
System.err.println("Not all placehorders of deleted entries are available");
}
}
My objective to get the friends contacts list from gmail and i have check no's of post for this Exception but no one is commented by correct solution.It's become blocker for me so please help me to out this problem and guide what is doing wrong at above code.

Android: Google Authentication + Ubertoken

Ok, I give up. Anyone have experience using Google's IssueAuthToken and MergeSession to authenticate with certain Google services that do not have official API access? In this case I'm trying to get Google bookmarks (from google.com/bookmarks).
I get the SID and LSID using getAuthToken and that works fine. I then call
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://accounts.google.com/IssueAuthToken?service=bookmarks&Session=false");
String url = ISSUE_AUTH_TOKEN_URL.buildUpon()
.appendQueryParameter("SID", sid)
.appendQueryParameter("LSID", lsid)
.build().toString();
I receive the "ubertoken".
I then do a GET to MergeSession and that's where it all goes wrong:
String url2 = "https://accounts.google.com/MergeSession?source=chrome&uberauth="+uberToken+"&service=bookmarks&continue=https%3A%2F%2Fwww.google.com%2Fbookmarks%2F";
HttpGet getCookies = new HttpGet(url2);
Looking through the headers of getCookies I am not seeing the extra cookies I should see, and I also see things like X-Frame-Options: DENY.
Help (please)!
Okay friends, here we go. It seems the above is now unreliable/broken at least occasionally as of August 2013. This is how I'm doing it now and it seems to work. It tries the above first, and if it fails, goes on to method #2.
final Account acct = am.getAccountsByType("com.google")[acctid];
final String tokenType = "weblogin:service=bookmarks&continue=https://www.google.com/bookmarks/";
am.getAuthToken(acct, tokenType, null, this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
final String accessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
if (accessToken.contains("WILL_NOT_SIGN_IN")) {
am.getAuthToken(acct, "SID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
sid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
am.getAuthToken(acct, "LSID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
lsid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
Thread t = new Thread() {
public void run() {
try {
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://www.google.com/accounts/IssueAuthToken?service=gaia&Session=false");
Uri TOKEN_AUTH_URL = Uri.parse("https://www.google.com/accounts/TokenAuth");
final HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
String url = ISSUE_AUTH_TOKEN_URL.buildUpon().appendQueryParameter("SID", sid).appendQueryParameter("LSID", lsid).build().toString();
HttpPost getUberToken = new HttpPost(url);
HttpResponse response = httpclient.execute(getUberToken);
String uberToken = EntityUtils.toString(response.getEntity(), "UTF-8");
final String accessToken2 = TOKEN_AUTH_URL.buildUpon()
.appendQueryParameter("source", "android-browser")
.appendQueryParameter("auth", uberToken)
.appendQueryParameter("continue", "https://www.google.com/bookmarks/").build().toString();
//do stuff
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}, null);
}
}, null);
} else {
//do stuff
}
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
finish();
}
}
}, null);

Get access token from google plus Android

Can anyone tell me what am I doing wrong? I need to get the access token from Google Plus..
I put this in my onConnected() method but I am not getting the access token, instead I am getting error...
Code:
try {
String token = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName() + "", "oauth2:" + Scopes.PLUS_PROFILE +
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
Log.d("AccessToken", token);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error:
08-07 10:10:24.199: E/GoogleAuthUtil(17203): Calling this from your main thread can lead to deadlock and/or ANRs
Can anyone tell me what would be the correct way to get the Google Plus access token from the user?
You need to put the request for a token in a background thread. I've posted some example code showing how to do it in this question:
"Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken" from GoogleAuthUtil(Google Plus integration in Android)
You can access token in onConnected() method. add this code onConnected() methods scope.
final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String ace = "";
try {
ace = GoogleAuthUtil.getToken(getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
}
catch (IOException e) {
e.printStackTrace();
}
catch (GoogleAuthException e) {
e.printStackTrace();
}
Log.i("", "mustafa olll " + ace);
return null;
}
}.execute();
You need to fetch it using async task.
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Log.i(TAG, "onConnected");
// Update the user interface to reflect that the user is signed in.
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
// Retrieve some profile information to personalize our app for the user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
System.out.print("email" + email);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT; }
Your access token will be stored into token variable.
Here is the code you can use. If someone has better suggestion then please post:
/**
* Successfully connected (called by PlusClient)
*/
#Override
public void onConnected(Bundle connectionHint) {
/* First do what ever you wanted to do in onConnected() */
....
....
/* Now get the token using and async call*/
GetGooglePlusToken token = new GetGooglePlusToken(this.getActivity(), mPlusClient);
token.execute();
}
class GetGooglePlusToken extends AsyncTask<Void, Void, String> {
Context context;
private GoogleApiClient mGoogleApiClient;
private String TAG = this.getClass().getSimpleName();
public GetGooglePlusToken(Context context, GoogleApiClient mGoogleApiClient) {
this.context = context;
this.mGoogleApiClient = mGoogleApiClient;
}
#Override
protected String doInBackground(Void... params) {
String accessToken1 = null;
try {
Bundle bundle = new Bundle();
String accountname = Plus.AccountApi.getAccountName(mGoogleApiClient);
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
accessToken1 = GoogleAuthUtil.getToken(context,
accountname,
scope);
return accessToken1;
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
//TODO: HANDLE
Log.e(TAG, "transientEx");
transientEx.printStackTrace();
accessToken1 = null;
} catch (UserRecoverableAuthException e) {
// Recover
Log.e(TAG, "UserRecoverableAuthException");
e.printStackTrace();
accessToken1 = null;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
Log.e(TAG, "GoogleAuthException");
authEx.printStackTrace();
accessToken1 = null;
} catch (Exception e) {
Log.e(TAG, "RuntimeException");
e.printStackTrace();
accessToken1 = null;
throw new RuntimeException(e);
}
Log.wtf(TAG, "Code should not go here");
accessToken1 = null;
return accessToken1;
}
#Override
protected void onPostExecute(String response) {
Log.d(TAG, "Google access token = " + response);
}
}

Listing Google Drive File on Android using Files.List() API

Currently i need to make an application that can list all of Google Drive file.
i already did the account choosing and oauth process, an already get the token. but when i try to use API call to list all my file on Google Drive (By using drive.files.list) i didn't get any result, the arraylist of files which is supposed to hold all the file is still empty. i also got error :
java.net.unknownHostException www.googleapis.com cannot be resolved
this is my code :
SharedPreferences settings = getSharedPreferences(PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", got.name);
editor.commit();
account=got;
amf=accMgr.getAuthToken(account, authTokenType, true,
new AccountManagerCallback<Bundle>(){
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle result;
Intent i;
String token;
Drive a;
result = arg0.getResult();
if (result.containsKey(accMgr.KEY_INTENT)) {
i = (Intent)result.get(accMgr.KEY_INTENT);
if (i.toString().contains("GrantCredentialsPermissionActivity")) {
// Will have to wait for the user to accept
// the request therefore this will have to
// run in a foreground application
cbt.startActivity(i);
} else {
cbt.startActivity(i);
}
}
else if (result.containsKey(accMgr.KEY_AUTHTOKEN)) {
accessProtectedResource.setAccessToken(result
.getString(accMgr.KEY_AUTHTOKEN));
buildService(result
.getString(accMgr.KEY_AUTHTOKEN),API_KEY);
/*else {
token = (String)result.get(AccountManager.KEY_AUTHTOKEN);*/
/*
* work with token
*/
// Remember to invalidate the token if the web service rejects it
// if(response.isTokenInvalid()){
// accMgr.invalidateAuthToken(authTokenType, token);
// }
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, handler);
}
private void buildService(final String authToken, final String ApiKey) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(ApiKey);
driveRequest.setOauthToken(authToken);
}
});
System.out.println(authToken);
service= b.build();
List<File> a=new ArrayList<File>();
try {
a = retrieveDriveFile(service);
System.out.println(a.size());
File c=a.get(0);
TextView ad=(TextView) findViewById(R.id.test);
ad.setText(c.getOriginalFilename());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> retrieveDriveFile(Drive service) throws IOException{
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error ssoccurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}
This would typically happen if you don't have a working internet connection on your device.
Also don't forget to add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
This could happen also if you are behind a proxy. If that's the case please have a look at this question.
If you want to get all the file from Goolge Drive. Assume that you have already done the Account Choosing process and creating Drive (Drive mService) etc.
Now Under Button Click Event call this function
ButtonClickEvent
{
GetDriveData();
}
// FUNCTION TO RETRIEVE GOOGLE DRIVE DATA
private void GetDriveData()
{
private List<File> mResultList;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
mResultList = new ArrayList<File>();
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.List request = null;
do
{
try
{
request = f1.list();
request.setQ("trashed=false");
com.google.api.services.drive.model.FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
}
catch (UserRecoverableAuthIOException e)
{
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
catch (IOException e)
{
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();//Calling to Populate Data to the List
}
});
t.start();
}
//Populating Retrieved data to List
private void populateListView()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
mFileArray = new String[mResultList.size()];
int i = 0;
for(File tmp : mResultList)
{
//System.out.println("FILE DATA "+tmp.getId()+"."+tmp.getFileSize()+".."+tmp.getFileExtension()+",,"+tmp.getMimeType()+"/"+tmp.getTitle());
mFileArray[i] = tmp.getTitle();
i++;
}
mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mFileArray);
mListView.setAdapter(mAdapter);
button2.setText("yes");
}
});
}

application force close on asynch task , on orientation change:android

i am using asynchronous task for doing some background operation as xml parsing on do in back ground, it works well , but on changing the origination of android device it causes force close , i Google on it , but don't any accordingly or can say unable to explore my self , please any one have idea about this share to me..i will be thankful of u ..
#Override
protected void **onPreExecute()** {
if(refreshFlage)
{
Log.i("refreshFlage","refreshFlage");
dialog = new ProgressDialog(ReplyForm.replyform);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
else
{
dialog = new ProgressDialog(QuestionScreen.questionscreen);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
#Override
protected void **onPostExecute**(final Boolean success) {
dialog.cancel();
try {
java.lang.System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}else {
try{
}
}
catch (NullPointerException e) {
// TODO: handle exception
}
}
}
#Override
protected Boolean **doInBackground**(final String... args) {
getQuestionsMethod();
return null;
}
private void getQuestionsMethod() {
// TODO Auto-generated method stub
HttpResponse response = null;
InputStream is = null;
JSONObject jsonObj = new JSONObject(result);
JSONObject jobj = jsonObj.getJSONObject("question");
group_subject = jobj.getString(TAG_SUBJECT);
question_id = jobj.getString(TAG_QUESTIONID);
author_name = jobj.getString(TAG_AUTHORNAME);
lastpost_date = jobj.getString(TAG_LASTPOSTDATE);
replies = jobj.getString(TAG_REPLIES);
newPost = jobj.getString(TAG_NEWPOST);
userCanReply = jobj.getString(TAG_USERCANREPLY);
poll = jobj.getString(TAG_POLL);
HashMap<String, Object> groupdetailData = new HashMap<String, Object>();
groupdetailData.put(TAG_SUBJECT, group_subject);
groupdetailData.put(TAG_QUESTIONID, question_id);
groupdetailData.put(TAG_AUTHORNAME, author_name);
groupdetailData.put(TAG_LASTPOSTDATE, lastpost_date);
groupdetailData.put(TAG_REPLIES, replies);
groupdetailData.put(TAG_POLL, poll);
groupdetailData.put(TAG_NEWPOST, newPost);
groupdetailData.put(TAG_USERCANREPLY, userCanReply);
int arrayCount = questiondetailarraylist.size();
if (arrayCount > 0) {
questiondetailarraylist.clear();
}
if (poll.equalsIgnoreCase("true")) {
pollmulti = jobj.getString(TAG_POLLMULTI);
pollsubject = jobj.getString(TAG_POLLSUBJECT);
Pollid = jobj.getString(TAG_POLLID);
groupdetailData.put(TAG_POLLMULTI, pollmulti);
groupdetailData.put(TAG_POLLSUBJECT, pollsubject);
groupdetailData.put(TAG_POLLID, Pollid);
//mDbHelper.insertPollfield(questionid, pollmulti, pollsubject, Pollid);
groupdetailData.put("PollTrueData", pollTrueVector);
//System.out.println("after poll method..");
}
//System.out.println(groupdetailData.size());
questiondetailarraylist.add(groupdetailData);
//System.out.println("11111111111111111");
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
answersHashMap.put("vectorArray", vectorArray);
answersHashMap.put("lastUpdateValue", lastUpdateValue);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
User showDialog(id) function for creating dialog, specially when screen orientation changes. More detail is here
On orientation change the activity is destroyed and recreated.
You'll need to handle this by adding the attribute: android:configChanges="orientation" in the AndroidManifest file to your current activity.

Categories

Resources