Can we implement Paypal with a card payment. e.g. Somebody doesn't have paypal account so he/she can pay using debit or credit card. Is there any way to implement paypal with card.
Please help.
Hi I know I am very late to answer this question but surely folks implementing Paypal in their app will get benefit from this!
Android SDK for Paypal does not support Card Payment but yes "Rest API sdk for Paypal" has the capability. Include this in your build.gradle: compile 'com.paypal.sdk:rest-api-sdk:1.2.5'
And then try the following method:
public static final String CLIENT_ID = "AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd";
public static final String CLIENT_SECRET = "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX";
/**
* #method getAccessToken is used to get AccessToken for performing authorised transcations
* #param clientId credential that we get when we register our application on https://developer.paypal.com/
* #param clientSecret credential that we get when we register our application on https://developer.paypal.com/
* #return String accessToken
*/
public static final String getAccessToken(String clientId, String clientSecret){
Log.i(TAG,"GetAccessToken called");
String accessToken = "";
long expiresIn;
try {
OAuthTokenCredential oAuthTokenCredential = new OAuthTokenCredential(clientId, clientSecret, getSdKConfig());
expiresIn = oAuthTokenCredential.expiresIn();
accessToken = oAuthTokenCredential.getAccessToken();
Log.i(TAG, "AccessToken: "+accessToken);
} catch (PayPalRESTException e) {
e.printStackTrace();
}
return accessToken;
}
/**
* #method makeDirectPayment is used for making direct payment via credit cards. Customers who don't have paypal account can pay via this method.
* #return String with Payment Id and Payment status
*/
public static final String makeDirectPayment(){
String accessToken = getAccessToken(Constants.CLIENT_ID, Constants.CLIENT_SECRET);
String message = "";
if (accessToken != null && !accessToken.equals("")){
APIContext apiContext = new APIContext(accessToken);
apiContext.setConfigurationMap(getSdKConfig());
CreditCard creditCard = new CreditCard();
creditCard.setType("visa");
creditCard.setNumber("4446283280247004");
creditCard.setExpireMonth(11);
creditCard.setExpireYear(2019);
creditCard.setFirstName("Test");
creditCard.setLastName("Shopper");
FundingInstrument fundingInstrument = new FundingInstrument();
fundingInstrument.setCreditCard(creditCard);
List<FundingInstrument> fundingInstrumentList = new ArrayList<>();
fundingInstrumentList.add(fundingInstrument);
Payer payer = new Payer();
payer.setFundingInstruments(fundingInstrumentList);
payer.setPaymentMethod("credit_card");
Amount amount = new Amount();
amount.setCurrency("EUR");
amount.setTotal("50");
Transaction transaction = new Transaction();
transaction.setDescription("Creating Direct Payment with Credit Card");
transaction.setAmount(amount);
List<Transaction> transactionList = new ArrayList<>();
transactionList.add(transaction);
Payment payment = new Payment();
payment.setIntent("sale");
payment.setTransactions(transactionList);
payment.setPayer(payer);
try {
Payment createdPayment = payment.create(apiContext);
if (createdPayment != null){
Log.i(TAG,"Payment object: "+createdPayment.toJSON());
message = "Payment Id: " + createdPayment.getId() + " Payment status: "+createdPayment.getState();
Log.i(TAG, message);
}
} catch (PayPalRESTException e) {
e.printStackTrace();
}
}
return message;
}
Note for simplicity I have used everything static but you can maintain your own UI to get no of items, its pricing, credit card details from user.
Related
PaytmOrder paytmOrder = new PaytmOrder(orderIdString, midString, txnTokenString, txnAmountString, callBackUrl);
TransactionManager transactionManager = new TransactionManager(paytmOrder, new
PaytmPaymentTransactionCallback(){
#Override
public void onTransactionResponse(Bundle bundle) {
Log.e("server response", ""+bundle);
String status = bundle.getString("STATUS");
String transactionid = bundle.getString("TXNID");
String amount = bundle.getString("TXNAMOUNT");
if(status!=null){
Log.e("STATUS", status);
}
}
The above is my code
I am getting the amount after transaction but remained at payment page .
Payment page is to redirecting me to my android app.
How to do this ?
Kindly use the below call back URL, the same URL mentioned on paytm developer docs as well.
For Staging
https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=<ORDER_ID>
For Production
https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=<ORDER_ID>
I am trying to use a Developer Authenticated Provider to login to my android app basing it loosely off of this demo: https://github.com/awslabs/aws-sdk-android-samples/tree/master/CognitoSyncDemo. I successfully logged in through our own backend got the idToken and subsequently got session credentials to access our AWS database. I then used those credentials to make a POST to the db.
But this only worked once, now I cannot get through again, without having changed any code. I am also using a generated SDK through http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk.html. I'm not sure if this is causing any errors.
Here is my DeveloperAuthenticationProvider:
public class AuthenticationProvider extends
AWSAbstractCognitoDeveloperIdentityProvider {
private static final String TAG = AuthenticationProvider.class.getSimpleName();
private static SocializeClient mSocializeClient;
private static final String developerProvider = Constants.AWS_PROVIDER_NAME;
private static final String cognitoSampleDeveloperAuthenticationAppEndpoint = UrlEndpoints.URL_DOMAIN;
public AuthenticationProvider(Context context, String accountId, String identityPoolId, Regions region) {
super(accountId, identityPoolId, region);
/*
* Initialize the client using which you will communicate with your
* backend for user authentication.
*/
AWSCredentialsProvider awsCredentialsProvider = new CognitoCachingCredentialsProvider(
context,
this,
region
);
ApiClientFactory factory = new ApiClientFactory()
.endpoint(cognitoSampleDeveloperAuthenticationAppEndpoint)
.credentialsProvider(awsCredentialsProvider);
mSocializeClient = factory.build(SocializeClient.class);
}
/*Only refreshes the login info, when it has expired*/
/*
* (non-Javadoc)
* #see com.amazonaws.auth.AWSCognitoIdentityProvider#refresh() In refresh
* method, you will have two flows:
*/
/*
* 1. When the app user uses developer authentication. In this case, make
* the call to your developer backend, from where call the
* GetOpenIdTokenForDeveloperIdentity API of Amazon Cognito service. Be sure to call update(), so as to
* set the identity id and the token received.
*/
/*
* 2.When the app user is not using the developer authentication, just call
* the refresh method of the AWSAbstractCognitoDeveloperIdentityProvider
* class which actually calls GetId and GetOpenIDToken API of Amazon
* Cognito.
*/
#Override
public String refresh() {
Log.i(TAG, "refresh");
// If there is a key with developer provider name in the logins map, it
// means the app user has used developer credentials
if (!loginsMap.isEmpty()
&& loginsMap.containsKey(developerProvider)) {
Log.i(TAG, "contains provider");
} else {
Log.i(TAG, "does not contain developer provider");
Map<String, String> logins = new HashMap<>();
logins.put(developerProvider, UserSingleton.imei);
setLogins(logins);
}
// TODO:: Temp code to login. Once available, need to add code to GetToken from SocializeClient
Login login = new Login();
login.setImei(UserSingleton.imei);
login.setPassword(UserSingleton.password);
LoginReponse loginReponse = mSocializeClient.socializeAuthLoginPost(login);
Log.i(TAG, "login response: " + loginReponse.getIdentityId() + " - token: " + loginReponse.getToken());
update(loginReponse.getIdentityId(), loginReponse.getToken());
Log.i(TAG, "updated");
return loginReponse.getToken();
}
/*
* (non-Javadoc)
* #see com.amazonaws.auth.AWSBasicCognitoIdentityProvider#getIdentityId()
*/
/*
* This method again has two flows as mentioned above depending on whether
* the app user is using developer authentication or not. When using
* developer authentication system, the identityId should be retrieved from
* the developer backend. In the other case the identityId will be retrieved
* using the getIdentityId() method which in turn calls Cognito GetId and
* GetOpenIdToken APIs.
*/
#Override
public String getIdentityId() {
Log.i(TAG, "getIdentityId");
identityId = CognitoSyncClientManager.credentialsProvider.getCachedIdentityId();
if (identityId == null) {
Log.i(TAG, "identityId is null");
if (!loginsMap.isEmpty()
&& loginsMap.containsKey(developerProvider)) {
Log.i(TAG, "grabbing identityId using logins map");
// TODO:: Temp code to login. Once available, need to add code to GetToken from SocializeClient
Login login = new Login();
login.setImei(loginsMap.get(developerProvider));
login.setPassword(UserSingleton.password);
LoginReponse loginReponse = mSocializeClient.socializeAuthLoginPost(login);
Log.i(TAG, "login response: " + loginReponse.getIdentityId() + " - token: " + loginReponse.getToken());
update(loginReponse.getIdentityId(), loginReponse.getToken());
return loginReponse.getIdentityId();
} else {
return super.getIdentityId();
}
} else {
return identityId;
}
}
/*
* (non-Javadoc)
* #see
* com.amazonaws.auth.AWSAbstractCognitoIdentityProvider#getProviderName()
* Return the developer provider name which you chose while setting up the
* identity pool in the Amazon Cognito Console
*/
#Override
public String getProviderName() {
return developerProvider;
}
/**
* This function validates the user credentials against the sample Cognito
* developer authentication application. After that it stores the key and
* token received from sample Cognito developer authentication application
* for all further communication with the application.
*
* #param imei
* #param password
*/
public void login(String imei, String password, Context context) {
Log.i(TAG, "login");
Login login = new Login();
login.setImei(imei);
login.setPassword(password);
new AuthenticationTask(context).execute(login);
}
public void publishProfile(Context context, Profile profile){
Log.i(TAG, "publishProfile");
ProfileKey profileKey = new ProfileKey();
profileKey.setUserID(identityId);
profile.setKey(profileKey);
new UploadProfileTask(context).execute(profile);
}
protected static SocializeClient getSocializeClientInstance() {
if (mSocializeClient == null) {
throw new IllegalStateException(
"Dev Auth Client not initialized yet");
}
return mSocializeClient;
}
}
Here is my AuthenticationTask as well where I attempt to login, then grab credentials to access the AWS database:
public class AuthenticationTask extends
AsyncTask<Login, Void, Void> {
private static final String TAG = AuthenticationTask.class.getSimpleName();
// The user name or the developer user identifier you will pass to the
// Amazon Cognito in the GetOpenIdTokenForDeveloperIdentity API
private String mImei;
private String mPassword;
private GetCredentialsForIdentityResult credentialsForIdentityResult;
private boolean isSuccessful;
private final Context context;
public AuthenticationTask(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(Login... params) {
Log.i(TAG, "doInBackground get refreshing threshold: " + CognitoCachingCredentialsProvider.DEFAULT_THRESHOLD_SECONDS);
mImei = params[0].getImei();
mPassword = params[0].getPassword();
Login login = params[0];
// if(mPassword == null){
// Log.i(TAG, "register");
// mPassword = Utils.generateRandomString();
// final Register register = new Register();
// register.setImei(mImei);
// register.setPassword(mPassword);
// login.setPassword(mPassword);
// RegisterResponse registerResponse = AuthenticationProvider.getSocializeClientInstance().socializeAuthRegisterPost(register);
// Log.i(TAG, "registerResponse: " + registerResponse.getCreated());
UserSingleton.password = mPassword;
UserSingleton.getInstance().saveRegistrationInfo();
Log.i(TAG, "imei: " + mImei);
// }
Log.i(TAG, "calling login post");
LoginReponse loginReponse = AuthenticationProvider.getSocializeClientInstance().socializeAuthLoginPost(login);
Log.i(TAG, "login response: " + loginReponse.getIdentityId() + " - token: " + loginReponse.getToken());
// Set up the loginsMap to send with the credentials request
Map<String, String> loginsMap = new HashMap<>();
loginsMap.put(CognitoSyncClientManager.developerIdentityProvider.getProviderName(), loginReponse.getToken());
// get AWS credentials to access DB
GetCredentialsForIdentityRequest credentialsForIdentityRequest = new GetCredentialsForIdentityRequest();
credentialsForIdentityRequest.setIdentityId(loginReponse.getIdentityId());
credentialsForIdentityRequest.setLogins(loginsMap);
Log.i(TAG, "credentials request: " + credentialsForIdentityRequest.getIdentityId() + credentialsForIdentityRequest.getLogins());
AmazonCognitoIdentityClient cognitoIdentityClient = new AmazonCognitoIdentityClient(CognitoSyncClientManager.credentialsProvider);
credentialsForIdentityResult = cognitoIdentityClient
.getCredentialsForIdentity(credentialsForIdentityRequest);
isSuccessful = credentialsForIdentityResult != null;
return null;
}
#Override
protected void onPostExecute(Void result) {
if (isSuccessful) {
Log.i(TAG, "accessKeyId: " + credentialsForIdentityResult.getCredentials().getAccessKeyId()
+ "\nsecretKey: " + credentialsForIdentityResult.getCredentials().getSecretKey()
+ "\nsessionToken: " + credentialsForIdentityResult.getCredentials().getSessionToken());
CognitoSyncClientManager
.addLogins(
((AuthenticationProvider) CognitoSyncClientManager.credentialsProvider
.getIdentityProvider()).getProviderName(),
mImei);
} else {
Log.i(TAG, "login error: " + result);
}
}
}
In my refresh call I am just relogging in. I'm not sure if that is correct.
The biggest issue now is upon startup when I attempt to login using, mSocializeClient.socializeAuthLoginPost(login) it seems to call refresh every time, before it even logs in. Refresh then attempts to login again and it keeps calling itself endlessly.
Any help/explanations would be greatly appreciated.
The way the dev auth sample works is as follows:
The DeveloperAuthenticationTask.login() is supposed to login to the server and get a session key.
It sets up the logins map and calls DeveloperAuthenticationProvider.refresh()
Refresh exchanges the session key with the server for a valid cognito token and identity id and calls update with the token and identity id.
In your case, you don't have this session key, just username and password. So you don't need the AuthenticationTask. All you need is:
a login() in your AuthenticationProvider, that puts the username/password in a secure location, sets up the login map and calls refresh (it shouldn't actually attempt to login to your service).
In refresh() you retrieve the username/pass from the secure location, call your service and then call update with the token and identity id returned from your service.
Can you simplify your code to this flow?
I am using webview to authenticate the user using this https://github.com/imellon/Google-Plus-Android-Sample/blob/master/src/com/imellon/android/googleplus/OAuthActivity.java to access my app and after he his succesfully authorized I need to get the user email.
I couldn't find out the way to get the email.
This is what I have now:
private void retrieveProfile() {
try {
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport transport = new NetHttpTransport();
SharedPreferencesCredentialStore credentialStore = SharedPreferencesCredentialStore
.getInstance(prefs);
AccessTokenResponse accessTokenResponse = credentialStore.read();
GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
accessTokenResponse.accessToken, transport, jsonFactory,
SharedPreferencesCredentialStore.CLIENT_ID,
SharedPreferencesCredentialStore.CLIENT_SECRET,
accessTokenResponse.refreshToken);
Builder b = Plus.builder(transport, jsonFactory)
.setApplicationName("Simple-Google-Plus/1.0");
b.setHttpRequestInitializer(accessProtectedResource);
Plus plus = b.build();
profile = plus.people().get("me").execute();
updateViews();
} catch (Exception ex) {
ex.printStackTrace();
}
}
This is how I get the Id, name and url
private void updateViews() {
Drawable image = loadImage(this, profile.getImage().getUrl());
profile_photo.setImageDrawable(image);
profile_id.setText("Id: " + profile.getId());
profile_name.setText("Name: " + profile.getDisplayName());
profile_url.setText("Url: " + profile.getUrl());
}
And finally each time when he logins to my app how do I check the session ?
Any help is greatly appreciated
Use profile.getEmails() as documented in https://developers.google.com/resources/api-libraries/documentation/plus/v1/java/latest/. The result is a list of type java.util.List<Person.Emails>.
You need to make sure your client asked for the scope plus.profile.emails.read to allow your client to retrieve that information.
I'm working on a multi-user Android application that provides to its users access to GMaps (find one another), chat and so on. Users should login to application using their accounts on Twitter, Facebook, Google+ etc. Everything works fine with all accounts except G+ - application can get access to G+ API only with its owner account. With other accounts I receive com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found or "authorization error". App is registered on the API Console, and OAuth2.0 authentication used. I use standard authentication mechanism from Google sites. Is it possible to use different G+ accounts to login?
Here is my code (Android v1.6):
public class GooglePlusActivity extends Activity {
public static final String LOG_TAG = GooglePlusActivity.class.getSimpleName();
public static final String EXTRA_FIRSTNAME = "firstname";
public static final String EXTRA_LASTNAME = "lastname";
public static final String EXTRA_NICKNAME = "nickname";
public static final String EXTRA_SEX = "sex";
public static final String EXTRA_AVATAR = "avatar";
public static final String EXTRA_ID_SOCNET = "id_socnet";
private ApplicationSettings mSettings;
private Person mProfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSettings = ((TomskApplication)getApplication()).getSettings();
signIn();
}
private void signIn() {
WebView webView = new WebView(this);
setContentView(webView);
webView.getSettings().setJavaScriptEnabled(false);
String googleAuthorizationRequestUrl = new GoogleAuthorizationRequestUrl(
mSettings.getGPID(), mSettings.getGPRedirectURI(),
mSettings.getGPScope()).build();
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if (url.startsWith(mSettings.getGPRedirectURI())) {
try {
Intent res_intent = new Intent();
if (url.indexOf("code=") != -1) {
String code = url.substring(mSettings
.getGPRedirectURI().length() + 7, url
.length());
AccessTokenResponse token = new GoogleAuthorizationCodeGrant(
new NetHttpTransport(),
new JacksonFactory(), mSettings.getGPID(),
mSettings.getGPSecret(), code, mSettings
.getGPRedirectURI()).execute();
mSettings.setGPToken(token);
// Loading user data
retrieveProfile();
if (mProfile == null) {retrieveProfile();}
res_intent.putExtra(EXTRA_FIRSTNAME, mProfile
.getName().getGivenName());
res_intent.putExtra(EXTRA_LASTNAME, mProfile
.getName().getFamilyName());
res_intent.putExtra(EXTRA_NICKNAME,
mProfile.getNickname());
res_intent.putExtra(EXTRA_SEX, mProfile.getGender());
res_intent.putExtra(EXTRA_AVATAR, mProfile
.getImage().getUrl());
res_intent.putExtra(EXTRA_ID_SOCNET, mProfile.getId());
setResult(Activity.RESULT_OK, res_intent);
view.setVisibility(View.INVISIBLE);
finish();
} else if (url.indexOf("error=") != -1) {
view.setVisibility(View.INVISIBLE);
setResult(Activity.RESULT_CANCELED);
finish();
}
} catch (IOException e) {
Log.d(LOG_TAG, e.toString());
}
return true;
} else {
return false;
}
}
});
webView.loadUrl(googleAuthorizationRequestUrl);
}
/**
* Retrieve user profile
*/
private void retrieveProfile() throws IOException {
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport transport = new NetHttpTransport();
AccessTokenResponse token = mSettings.getGPToken();
GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
token.accessToken, transport, jsonFactory,
mSettings.getGPID(), mSettings.getGPSecret(),
token.refreshToken);
Builder b = Plus.builder(transport, jsonFactory)
.setApplicationName("MyApp/1.0");
b.setHttpRequestInitializer(accessProtectedResource);
Plus plus = b.build();
mProfile = plus.people().get("me").execute();
}
}
I've searched on Google sites, Stack Overflow but found nothing. Please help.
Dont know that this will help but, if you are desperate....
New release of some of the Android client side libs on 4/4/2012 here
and there is fresh Google+ sample, using some reconfigured classes in the main() method where they access protected resources. The new version in R 1.8 is different than your code , at least at the top of the stack.... IMO the use in the new example of the Credential class and of the PLUS.Builder is probably going to boil down to pretty much the same implementation that you already have. You may want to look at the newer sample if you cannot get anything else to work.
new code from googlePlus sample in 1.8
public static void main(String[] args) {
try {
try {
// authorization
Credential credential = OAuth2Native.authorize(
HTTP_TRANSPORT, JSON_FACTORY, new LocalServerReceiver(),
Arrays.asList(PlusScopes.PLUS_ME));
// set up global Plus instance
plus = Plus.builder(HTTP_TRANSPORT, JSON_FACTORY)
.setApplicationName("Google-PlusSample/1.0").setHttpRequestInitializer(credential)
.build();
older code here
I am working on an Android Honeycomb (v3.0) application that has a requirement of communicating with the Google Calendar API. I would like to allow my application to access a particular Google account's Calendar data in order to read and create events.
Unfortunately, I ran into a problem with authorization using OAuth2. Here's what I have so far:
1) The Google account whose calendar I would like to access is registered within the Android device I am working with.
2) I enabled the Calendar API within the Google APIs Console on the account.
3) I am able to access this account using the following code:
AccountManager accountManager = AccountManager.get(this.getBaseContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
Account acc = accounts[0]; // The device only has one account on it
4) I would now like to obtain an AuthToken for use when communicating with the calendar. I followed this tutorial, but converted everything to work with Google Calendar instead of Google Tasks. I successfully retrieve an authToken from the AccountManager with the account I would like to use by using getAuthToken with AUTH_TOKEN_TYPE == "oauth2:https://www.googleapis.com/auth/calendar".
5) Here's where the problems begin. I am now at this point:
AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(tokens[0]); // this is the correct token
HttpTransport transport = AndroidHttp.newCompatibleTransport();
Calendar service = Calendar.builder(transport, new JacksonFactory())
.setApplicationName("My Application's Name")
.setHttpRequestInitializer(accessProtectedResource)
.build();
service.setKey("myCalendarSimpleAPIAccessKey"); // This is deprecated???
Events events = service.events().list("primary").execute(); // Causes an exception!
6) Here's the exception returned by the last line:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "usageLimits",
"message" : "Daily Limit Exceeded. Please sign up",
"reason" : "dailyLimitExceededUnreg",
"extendedHelp" : "https://code.google.com/apis/console"
} ],
"message" : "Daily Limit Exceeded. Please sign up"
}
7) According to this Google API Video (wait a minute or so to get to the applicable content), a reason for this exception may be the fact that I did not enable the API access within the Google APIs Console for the account. However, if you look at 2), you can see that I did do so.
8) To me, it seems that the problem is that I was unable to set the Simple API Access Key correctly, because the Calendar.setKey method is deprecated. Within the Google Tasks tutorial that I previously linked, the key is set using Tasks.accessKey = "key". I'm not sure how to get this working with the Calendar API, though. I have tried multiple Google accounts, which all came up with the exception from 5).
9) I would like to point out that the traditional method of using OAuth2 did work for me. Here's the code I used for that:
HttpTransport TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
String SCOPE = "https://www.googleapis.com/auth/calendar";
String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";
String CLIENT_ID = "myClientID";
String CLIENT_SECRET = "myClientSecret";
String authorizeUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID, CALLBACK_URL, SCOPE).build();
String authorizationCode = "???"; // At this point, I have to manually go to the authorizeUrl and grab the authorization code from there to paste it in here while in debug mode
GoogleAuthorizationCodeGrant authRequest = new GoogleAuthorizationCodeGrant(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authorizationCode, CALLBACK_URL);
authRequest.useBasicAuthorization = false;
AccessTokenResponse authResponse = authRequest.execute();
String accessToken = authResponse.accessToken; // gets the correct token
GoogleAccessProtectedResource access = new GoogleAccessProtectedResource(accessToken, TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authResponse.refreshToken);
HttpRequestFactory rf = TRANSPORT.createRequestFactory(access);
AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);
HttpTransport transport = AndroidHttp.newCompatibleTransport();
Calendar service = Calendar.builder(transport, new JacksonFactory())
.setApplicationName("My Application's Name")
.setHttpRequestInitializer(accessProtectedResource)
.build();
Events events = service.events().list("primary").execute(); // this works!
10) Finally, my question: I would like to use the account from the AccountManager on the device itself in order to retrieve a working OAuth2 token for use with the Google Calendar API. The second method is not useful for me, because the user will have to manually go to their web browser and get the authorization code, which is not user friendly. Anyone have any ideas? Apologies for the long post, and thanks!
Try adding a JsonHttpRequestInitializer to the builder and setting your key there:
Calendar service = Calendar.builder(transport, new JacksonFactory())
.setApplicationName("My Application's Name")
.setHttpRequestInitializer(accessProtectedResource)
.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
public void initialize(JsonHttpRequest request) {
CalendarRequest calRequest = (CalendarRequest) request;
calRequest.setKey("myCalendarSimpleAPIAccessKey");
}
}).build();
To answer no 10 : I've basically had to do what you had to do working with the TaskSample and then use the Android GData Calendar Sample available here : http://code.google.com/p/google-api-java-client/source/browse/calendar-android-sample/src/main/java/com/google/api/client/sample/calendar/android/CalendarSample.java?repo=samples
to get the AuthToken from the AccountManager itself:
accountManager = new GoogleAccountManager(this);
settings = this.getSharedPreferences(PREF, 0);
gotAccount();
private void gotAccount() {
Account account = accountManager.getAccountByName(accountName);
if (account != null) {
if (settings.getString(PREF_AUTH_TOKEN, null) == null) {
accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE,
true, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
if (bundle
.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle
.getParcelable(AccountManager.KEY_INTENT);
int flags = intent.getFlags();
flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
intent.setFlags(flags);
startActivityForResult(intent,
REQUEST_AUTHENTICATE);
} else if (bundle
.containsKey(AccountManager.KEY_AUTHTOKEN)) {
setAuthToken(bundle
.getString(AccountManager.KEY_AUTHTOKEN));
// executeRefreshCalendars();
}
} catch (Exception e) {
handleException(e);
}
}
}, null);
} else {
// executeRefreshCalendars();
}
return;
}
chooseAccount();
}
private void chooseAccount() {
accountManager.manager.getAuthTokenByFeatures(
GoogleAccountManager.ACCOUNT_TYPE, AUTH_TOKEN_TYPE, null,
ExportClockOption.this, null, null,
new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
Bundle bundle;
try {
bundle = future.getResult();
setAccountName(bundle
.getString(AccountManager.KEY_ACCOUNT_NAME));
setAuthToken(bundle
.getString(AccountManager.KEY_AUTHTOKEN));
// executeRefreshCalendars();
} catch (OperationCanceledException e) {
// user canceled
} catch (AuthenticatorException e) {
handleException(e);
} catch (IOException e) {
handleException(e);
}
}
}, null);
}
void setAuthToken(String authToken) {
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_AUTH_TOKEN, authToken);
editor.commit();
createCalendarService(authToken);
try {
Events events = service.events().list("primary").execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void createCalendarService(String authToken) {
accessProtectedResource = new GoogleAccessProtectedResource(authToken);
Log.i(TAG, "accessProtectedResource.getAccessToken() = "
+ accessProtectedResource.getAccessToken());
JacksonFactory jsonFactory = new JacksonFactory();
service = com.google.api.services.calendar.Calendar
.builder(transport, jsonFactory)
.setApplicationName("Time Journal")
.setJsonHttpRequestInitializer(
new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) {
CalendarRequest calendarRequest = (CalendarRequest) request;
calendarRequest
.setKey("<YOUR SIMPLE API KEY>");
}
}).setHttpRequestInitializer(accessProtectedResource)
.build();
}