How to get the paytm payment response - android

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>

Related

Razorpay Error - {"code":"BAD_REQUEST_ERROR","description":"ay_order_id is not a valid id"}

I'm implement Razorpay with PaymentResultWithDataListener. Actually i need order_id and signature so i use PaymentResultWithDataListener not used PaymentResultListener because there are no option to get order_id and signature. And I have follow these links
https://docs.razorpay.com/v1/page/orders#verifying-the-signature
https://razorpay.com/mobile/
https://github.com/razorpay/razorpay-android-sample-app
But not getting any solution.
Menifest File
<meta-data
android:name="com.razorpay.ApiKey"
android:value="rzp_test_PLbERPkkqGZkOF" />
build.gradle
api 'com.razorpay:checkout:1.5.4'
I got an error
{"code":"BAD_REQUEST_ERROR","description":"ay_order_id is not a valid id"}
I am trying with this code
public class CheckoutActivity extends AppCompatActivity implements View.OnClickListener, PaymentResultWithDataListener {
private static final String TAG = CheckoutActivity.class.getSimpleName();
Button mCheckOutView;
String OrderId = "";
String signature = "";
String order_id = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_method);
Checkout.preload(getApplicationContext());
mCheckOutView = findViewById(R.id.check_out);
mCheckOutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == mCheckOutView) {
startPayment();
}
}
public void startPayment() {
/*
You need to pass current activity in order to let Razorpay create CheckoutActivity
*/
final Activity activity = this;
final Checkout co = new Checkout();
try {
JSONObject options = new JSONObject();
options.put("name","Test");
options.put("description", getString(R.string.app_name));
options.put("key", getString(R.string.api_key));
options.put("order_id","razorpay_order_id");
options.put("signature","razorpay_signature");
options.put("currency", "INR");
options.put("amount", 100);
JSONObject preFill = new JSONObject();
preFill.put("email", "test#gmail.com");
preFill.put("contact", "9999999999");
options.put("prefill", preFill);
JSONObject notesData=new JSONObject();
notesData.put("Order Id","order123");
notesData.put("address","Test Address");
options.put("notes", notesData);
JSONObject theme=new JSONObject();
theme.put("color","#738598");
theme.put("emi_mode",true);
options.put("theme", theme);
co.open(activity, options);
} catch (Exception e) {
Toast.makeText(activity, "Error in payment: " + e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public void onPaymentSuccess(String s, PaymentData paymentData) {
String paymentId = paymentData.getPaymentId();
String signature = paymentData.getSignature(); // got null
String orderId = paymentData.getOrderId(); // got null
}
#Override
public void onPaymentError(int i, String s, PaymentData paymentData) {
Log.e(TAG,s); //error {"code":"BAD_REQUEST_ERROR","description":"ay_order_id is not a valid id"}
}
}
If i remove these 2 lines then this error not comes.
options.put("order_id","razorpay_order_id");
options.put("signature","razorpay_signature");
But paymentData.getSignature() and paymentData.getOrderId() is null.
Any help will be appreciated.
options.put("order_id","**razorpay_order_id**");
you need to generate this order_id from razorpay Order_ID API, only after this order_id which comes as a response from the API you would be able to process smoothly. After getting this Order_id from API, send it in above code in value (in place of razorpay_order_id)
options.put("signature","razorpay_signature");
This is not required in request. This will be generated at your server and will be used when a response is received in PaymentResultWithDataListener function. Read Signature generation method in official Documentation here : https://razorpay.com/docs/payment-gateway/android-integration/standard/
According to the official docs, by the time you start the checkout, you get the order_id when the merchant's backend starts an order with the RazorPay backend.
See the diagram here`.
As for the signature, according with the docs that's not something you put but something that comes from server responses and which you have to validate on your end. Check this

Microsoft Azure Mobile authentication with Google provider SDK in Android

I am currently testing Microsoft Azure and the App Service/Mobile Apps feature using a native Android app and C# on the back end.
I started with the Getting Started application (ToDo) as the base app and now I am trying to enable Authentication using the https://azure.microsoft.com/en-us/documentation/articles/app-service-authentication-overview/ page and Google as the provider.
So far I have
created a Google project with a OAuth Web client
the authorized redirect uri set there is: https://.azurewebsites.net/.auth/login/google/callback
in the Azure portal and the App Service instance I have enabled Authorization/Authentication
the "Action to take when request is not authenticated" option is set to "Allow Request"
For the Google Provider I have set the Client Id and Client Secret
In the Android app I am using the GoogleApiClient class to let the user select a Google Account. Also I get the ID token and the Server Auth Code
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(getString(R.string.server_client_id))
.requestServerAuthCode(getString(R.string.server_client_id))
.build();
mScopes = gso.getScopeArray();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
Once the user picks up an account I retrieve the token and code and then I ask for an access token using the GoogleAuthUtil class. After I get the access_token I try to exchange it with an App Service token (authenticate2 method)
private void handleSignInResult(GoogleSignInResult result) {
Log.d("", "handleSignInResult: " + result.isSuccess());
if(result.isSuccess()) {
final GoogleSignInAccount account = result.getSignInAccount();
final String idToken = account.getIdToken();
String serverAuthCode = account.getServerAuthCode();
mSignInButton.setVisibility(View.GONE);
mGoogleUserText.setText(account.getDisplayName());
mGoogleUserText.setVisibility(View.VISIBLE);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("idToken", idToken).commit();
prefs.edit().putString("serverAuthCode", serverAuthCode).commit();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
StringBuilder scopesBuilder = new StringBuilder("oauth2:");
for(Scope scope : mScopes) {
scopesBuilder//.append("https://www.googleapis.com/auth/")
.append(scope.toString())
.append(" ");
}
String token = GoogleAuthUtil.getToken(ToDoActivity.this,
account.getEmail(), scopesBuilder.toString());
return token;
} catch (IOException | GoogleAuthException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ToDoActivity.this);
prefs.edit().putString("accessToken", result).apply();
authenticate2();
}
}.execute();
} else {
mSignInButton.setVisibility(View.VISIBLE);
mGoogleUserText.setVisibility(View.GONE);
}
}
private void authenticate2() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String idToken = prefs.getString("idToken", null);
String serverAuthCode = prefs.getString("serverAuthCode", null);
String accessToken = prefs.getString("accessToken", null);
JsonObject json = new JsonObject();
json.addProperty("access_token", accessToken);
json.addProperty("id_token", idToken);
json.addProperty("authorization_code", serverAuthCode);
ListenableFuture<MobileServiceUser> loginFuture =
mClient.login(MobileServiceAuthenticationProvider.Google, json);
Futures.addCallback(loginFuture, new FutureCallback<MobileServiceUser>() {
#Override
public void onSuccess(MobileServiceUser result) {
createTable();
}
#Override
public void onFailure(Throwable t) {
Log.e(TAG, t.getMessage(), t);
}
});
}
So I am using the MobileServiceClient.login() method to send back to the server the access_token of the user in order to get back an Azure session.
Nevertheless, this call fails and I get back a MobileServiceException:
com.microsoft.windowsazure.mobileservices.MobileServiceException: You do not have permission to view this directory or page.
Any ideas what am I missing here?
Thanks
Well this is more than embarassing :-)
I first tried to "manually" verify the id_token using the Google tokeninfo endpoint:
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=
but I was getting a generic error that didn't give a lot of info.
Then I used the Google API Java client library and created a small test to verify my token (more info here: https://developers.google.com/identity/sign-in/android/backend-auth)
That test was failing as well and I realized that the reason for that was the expiring time of my token which was smaller than the current time. And this was happening because my emulator time was not correct!
When I set the "correct" timezone everything worked as expected.
Sorry for the post guys. You can use the code here as a template and don't forget to check your emulator time :-)

Laravel RESTful API with Android app

I'm developing an Android app and a RESTful API with Laravel 5 Framework.
I've got a trouble with the login activity: the flow is that the user ask a 8th characters code and the server web sends him a SMS with it. Then user can do the login using this code like a password.
This is the code that asks a code:
private void askCode(String mobile) {
GsonRequest<String> jsObjRequest = new GsonRequest<String>(
Request.Method.GET,
WebAPIRoute.authGetCode + "/" + mobile,
String.class, null,
new Response.Listener<String>() {
#Override
public void onResponse(String code) {
txtResponse.setText("Code asked successfully.");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getBaseContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
this.requestQueue.add(jsObjRequest);
}
And this the method in the RESTful API to generate a code:
public function getCode($mobileNum)
{
//genero un numero casuale da mandare con l'sms
$code = mt_rand(10000000, 99999999);
Session::put('code', $code);
sendCode($mobileNum, $code); //send code by SMS
return response()->json(array("success"=>true));
}
The code generated is stored into Laravel's Session (configurated with file driver).
When the user wants to login, the app call this method:
private void saveUser(final String code, final String mobile, final String name) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("nickname", name);
params.put("mobile", mobile);
params.put("code", code);
GsonRequest<String> jsObjRequest = new GsonRequest<String>(
Request.Method.POST,
WebAPIRoute.authValidateCode,
String.class,
params,
new Response.Listener<String>() {
#Override
public void onResponse(String authtoken) {
final Account account = new Account(accountName, mAccountType);
String authtokenType = mAuthTokenType;
// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
mAccountManager.addAccountExplicitly(account, code, null);
mAccountManager.setAuthToken(account, authtokenType, authtoken);
Bundle data = new Bundle();
data.putString(AccountManager.KEY_ACCOUNT_NAME, accountName);
data.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
data.putString(PARAM_USER_PASS, code);
data.putBoolean(ARG_IS_ADDING_NEW_ACCOUNT, true);
final Intent res = new Intent();
res.putExtras(data);
setAccountAuthenticatorResult(res.getExtras());
Intent i = new Intent(getBaseContext(), MyEventsActivity.class);
startActivity(i);
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e(TAG, volleyError.getMessage(), volleyError);
showMessage("Errore nell'autenticazione. Riprova piu` tardi.");
}
});
requestQueue.add(jsObjRequest);
}
The method of API that validate the code is this:
public function validateCode() {
$code = trim(Input::get('code'));
$nickName = trim(Input::get('nickname'));
$phoneNum = trim(Input::get('mobile'));
if (empty($phoneNum))
abort(400, 'mobile parameters not provided.');
if (empty($code))
abort(400, 'code parameters not provided.');
if (empty($nickName))
abort(400, 'nickname parameters not provided.');
$validCode = Session::get('code');
Log::info('code: ' . $code . " validCode: " . $validCode);
if($code == $validCode) {
Session::forget('code');
// Retrieve the user by the attributes, or instantiate a new instance...
$user = User::firstOrCreate(['Mobile' => $phoneNum]);
//aggiorno i campi nickname e password col nuovo codice
$user->Nickname = $nickName;
$user->password = $code;
//save!
$user->save();
//viene usata l'autenticazione di Laravel e gli serve una password
$token = JWTAuth::attempt(['Mobile' => $phoneNum, 'password' => $code]);
return response()->json($token);
} else {
//return response()->json(array('success' => false, 'error' => 'The code isn\'t correct.'));
abort(401, 'The code isn\'t correct.' . $validCode);
}
}
I've tested the RESTful API with Chrome and Firefox and the login works. With the app no. Infact the issue is that Session::get('code'); in validateCode returns always an empty value. I checked the Session file generated with Session::put('code', $code); and is correct. But when Session::get('code') is called, Laravel generates another Session file and seems not use the previous.
I disabled the CSRF Middleware in RESTful API.
What is wrong?
Storing the session on the server side is pointless. API's are suppose to be stateless so the second you finish the first request for the code and store it in a session on the server side, the session will end and the next request will not remember anything you set.
If you wanted to keep the code login and avoid using tokens, then you will have to send a unique code from the android app which identifies the user. Then generate the code on the server side and store it in a table with user_identifier and generated_code and create a model to access it e.g.
AttemptedLogin
user_id | generatedCode
0001 | 87392042
0032 | 83214320
Then on add this to saveUser
params.put("user_id", user_id); // can be the android device ID or even a unique timestamp
Finally on the server side in validateCode replace $validCode line with the following:
$user_id = trim(Input::get('user_id'));
....
$validCode = AttemptedLogin::where('user_id', $user_id)->first();
if($code == $validCode->generatedCode) {
$validCode->delete();
....

How to track Facebook appRequest that send from Unity app?

I want to track invites that send from "player_1" to other players to count them and as result give "player_1" some reward. Like in PVZ2.
Ok, Facebook have SDK for Unity3d. Here is API to call App request dialog that allow to invite player:
public static void AppRequest(
string message,
string[] to = null,
string filters = "",
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
Facebook doc says something about redirect_url that could be used to track user's that accept indentations:
https://developers.facebook.com/docs/reference/dialogs/requests/
But Unity plugin doesn't have this param.
Also doc says that follow:
Requests are only available for games on Facebook.com or iOS and
Android apps. Accepting a request from a game will direct the person
to the Canvas Page URL of the app that sent the Request. For native
mobile apps, accepting the request will direct the person to the app
on their device if installed or to the appropriate location (Apple App
Store or Google Play) to download the app otherwise.
Game is going to work on mobile devices only. Therefore we don't need to make Facebook Canvas application. Should I implement this Canvas URL script on our website anyway?
Where is the correct place to inject code (server side script) to track Facebook app requests?
UPDATE:
Thanks to Bhavesh Vadalia for answer: https://stackoverflow.com/a/21597185/425707
I've decided to not handle friends requests in Canvas App.
Here is solution for Facebook SDK 5.0.3:
// Quesry string: "/fql?q=SELECT uid, name, is_app_user, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1";
string q = "/fql?q=SELECT+uid,+name,+is_app_user,+pic_square+FROM+user+WHERE+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1+=+me())+AND+is_app_user+=+1";
FB.API(q, Facebook.HttpMethod.GET, friendsResult =>
{
if (friendsResult.Error != null)
{
FbDebug.Error(friendsResult.Error);
}
else
{
FbDebug.Log(friendsResult.Text);
}
});
Here is implement for track code using facebook graph api implement in for my application. hope it also help to you.
I am using facebook 3.6 sdk
private void requestMyAppFacebookFriends(Session session) {
Request friendsRequest = createRequest(session);
friendsRequest.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
List<GraphUser> friends = getResults(response);
Log.e("RESULT : ", "#"+friends.size());
for(int i =0;i<friends.size(); i++){
GraphUser user = friends.get(i);
boolean installed = false;
if(user.getProperty("installed") != null){
installed = (Boolean) user.getProperty("installed");
}
if(installed){
Log.e("USER NAME", "#"+friends.get(i).getId());
}
}
// TODO: your code here
}
});
friendsRequest.executeAsync();
}
private Request createRequest(Session session) {
Request request = Request.newGraphPathRequest(session, "me/friends", null);
Set<String> fields = new HashSet<String>();
String[] requiredFields = new String[] { "id", "name", "picture","installed" };
fields.addAll(Arrays.asList(requiredFields));
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}

Google Calendar API OAuth2 Troubles on Android Honeycomb

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();
}

Categories

Resources