PayPal Android Sdk Vault - android

My requirement is to store credit card details in Paypal vault using Android.
I followed these link
https://github.com/paypal/PayPal-Java-SDK
https://github.com/paypal/PayPal-Android-SDK
https://developer.paypal.com/docs/integration/direct/rest-vault-overview/
there is no mention on how to vault a credit using Android sdk. I think it can be done using their Rest API. How do I achieve this in Android?

You can store credit card in paypal using vault api Follow this steps
Step 1: Generate Access Token By OAuth Token Request
Try in postman
Url :- https://api.sandbox.paypal.com/v1/oauth2/token
Headers :- (Key,Value)
1.(Accept , application/json)
2.(Accept-Language , en_US)
3.(Content-Type , application/x-www-form-urlencoded)
4.(Authorization , Basic<Space>(here your code generated by postman))
Note :- Generate a Basic Auth in post man by select authorization tab ==> Basic Auth and enter paypal Client secret and Client id.
Body :- (Key,Value)
1.(grant_type,client_credentials)
Note :- Select x-www-form-urlencoded in body tab in postman
Step 2: Store credit card using valut api
Try in postman
Url :- https://api.sandbox.paypal.com/v1/vault/credit-cards
Headers :- (Key,Value)
1.(Accept , application/json)
2.(Accept-Language , en_US)
3.(Content-Type , application/x-www-form-urlencoded)
4.(Authorization , Bearer(your Access Token))
Body : (Json)
{
"payer_id": "user12345",
"type": "visa",
"number": "4111111111111111",
"expire_month": "11",
"expire_year": "2018",
"first_name": "Joe",
"last_name": "Shopper",
"billing_address": {
"line1": "52 N Main ST",
"city": "Johnstown",
"state": "OH",
"postal_code": "43210",
"country_code": "US"
}
}
Note :- Select raw tab in body in postman.

Thanks to vishal for his help. I was able to solve this using retrofit (adding headers statically).
1. First get the value of your authorization header:
String clientId = "your client id";
String clientSecret = "your client secret";
String credentials = clientId + ":" + clientSecret;
String basic =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
Log.e("Authorization",basic);
Copy this value from log, it will be used later in our solution.
2. Make the response model according to this json:
{
"scope":"https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.*",
"access_token":"Access-Token",
"token_type":"Bearer",
"app_id":"APP-6XR95014SS315863X",
"expires_in":28800
}
3. Make retorfit call method as this:
#Headers({
"Accept: application/json",
"Accept-Language : en_US",
"Content-Type : application/x-www-form-urlencoded",
"Authorization:your basic string value here"
})
#POST("https://api.sandbox.paypal.com/v1/oauth2/token/")
Call<AuthenticationTokenModel> getAuthentionToken(#Query("grant_type") String grant_type);
4. Finally make the call as:
ApiInterface apiInterface= ApiClient.getClient().create(ApiInterface.class);
apiInterface.getAuthentionToken("client_credentials").enqueue(new Callback<AuthenticationTokenModel>() {
#Override
public void onResponse(Call<AuthenticationTokenModel> call, Response<AuthenticationTokenModel> response) {
Log.e("response",response.body().getAccess_token());
}
#Override
public void onFailure(Call<AuthenticationTokenModel> call, Throwable t) {
Log.e("response",t.getMessage());
}
});
Thanks.
Edited:
You can also add dynamic headers to requests in Retrofit 2.
Follow this:
https://futurestud.io/tutorials/retrofit-add-custom-request-header

Related

how to post html tag in retrofit android

I need to use the following format payload in post method in retrofit. I need to post html tags as string. If we can't do this in retrofit, how can we do that?
{
"text": "<p>ffsdsdf <span class=\"mention\" data-index=\"0\" data-denotation-char=\"#\" data-id=\"12fe9af4-e2d6-47cb-9601-64c7a1fe9c4a\" data-value=\"Vendor 3 company Vendor\"><span contenteditable=\"false\"><span class=\"ql-mention-denotation-char\">#</span>Vendor 3 company Vendor</span></span> </p>",
"users": ["12fe9af4-e2d6-47cb-9601-64c7a1fe9c4a"]}
Update:
All I need to create a tag according to the number of users I get.
public interface placeApi {
#GET("/{id}")
public void getDataAPICall(#EncodedPath("text") TypedString text,
Callback<Model> response);
}
Try this.

Retrofit Dynamic JSON response

I'm new to JSON handling with retrofit but I've run into a problem.
We're making a prototype smart assistant chatbot with Dialogflow.
My Android Client sends a POST request to Google Dialogflow, which will call third party API's and send a response back.
However, this response depends on the type of intent detected by Dialogflow.
It can be nearly everything from music to weather information etc.
So the parameters (for the visualization) will be completely different and I don't know the type of response in advance.
I preprocess the response from Dialogflow in my own cloud function and send it back containing only the necessary fields for the client.
For example:
"What is the weather today in Brussels?"
Response:
{
"sessionId": "123456789",
"keepAlive": true,
"intentId": 100,
"intentName": "Weer",
"text": "Het weer in Hanoi is helder met een temperatuur van 23.2 graden.",
"Parameters": {
"text": {
"stringValue": "helder",
"kind": "stringValue"
},
"city": {
"stringValue": "Hanoi",
"kind": "stringValue"
},
"temp": {
"numberValue": 23.2,
"kind": "numberValue"
},
"intentId": {
"numberValue": 100,
"kind": "numberValue"
}
}
}
You can see the Parameters of the response depend on the type of intent(id). there can be many or zero parameters depending on the intent.
How can I make a Pojo for every type of response, not only the weather?
Or can I make a switch case based on intentId or something?
You can use generics than
public class Response<T> {
private String responseId;
private String sessionId;
private boolean keepAlive;
private float intentId;
private String intentName;
private String text;
private String Audio;
private T Parameters;
}
and when you want to create the object you can
new Response<YourClass>();
Your class will be the class as per your intent id

GraphQL server returns a 422 Error when request sent from Android app via Apollo Client

Hi I've been trying to set up a simple Android app to send a query to a GraphQL server I set up on my localhost via Springboot. If I don't use the app to send a request, either through GraphiQL or Postman, everything is fine and I have absolutely no issues. It's only when I send the request in the app through an Apollo Client that I get a 422 error.
I've set up log statements in Springboot that hosts the GraphQL server to log the payload.
Here's the schema as defined in Springboot.
type Query {
bookById(id: ID): Book
}
type Book {
id: ID
name: String
pageCount: Int
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
}
Here's the query as defined in AndroidStudio for the Apollo Client to work with.
query BookById($id : ID) {
bookById(id : $id){
name
author{
firstName
lastName
}
}}
Here's the code in Android Studio.
public class MainActivity extends AppCompatActivity {
private static final String BASE_URL = "http://xxx.xxx.xxx.xxx:8080/graphql";
private static final String TAG = "MainActivity";
private TextView textBox;
private Button queryButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textBox = (TextView) findViewById(R.id.plainbox);
queryButton = (Button) findViewById(R.id.queryButton);
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
ApolloClient apolloClient = ApolloClient.builder()
.serverUrl(BASE_URL)
.okHttpClient(okHttpClient)
.build();
// To make requests to our GraphQL API we must use an instance
// of a query or mutation class generated by Apollo.
Input<String> id = Input.fromNullable("book-1");
BookByIdQuery bq = BookByIdQuery.builder()
.id("book-1")
.build();
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "REGISTERED CLICK");
Log.d(TAG, "Book Query: " + bq.queryDocument());
apolloClient.query(bq).enqueue(new
ApolloCall.Callback<BookByIdQuery.Data>() {
#Override
public void onResponse(#NotNull com.apollographql.apollo.api.Response<BookByIdQuery.Data> dataResponse){
Log.d(TAG, "Got Response: \n" + dataResponse.toString());
// changing UI must be on UI thread
textBox.setText(dataResponse.data().toString());
}
#Override
public void onFailure(#NotNull ApolloException a){
Log.d(TAG, "Failed, ApolloException " + a);
}
}); // end apolloClient query
}
});
}
Here's the log on the server side I get if making a request via GraphiQL or Postman.
DEBUG 13749 --- [nio-8080-exec-8] o.s.w.f.CommonsRequestLoggingFilter : Before request [uri=/graphql]
Here's the log when the request comes from Apollo in the app.
DEBUG 13749 --- [io-8080-exec-10] o.s.w.f.CommonsRequestLoggingFilter : Before request [uri=/graphql]
DEBUG 13749 --- [io-8080-exec-10] o.s.w.f.CommonsRequestLoggingFilter : REQUEST DATA : uri=/graphql;payload={"operationName":"BookById","variables":{"id":"book-1"},"query":"query BookById($id: ID) { bookById(id: $id) { __typename name author { __typename firstName lastName } }}"}]
Could the issue be related to the __typename attribute that Apollo is adding? Or could it be due to "id" being defined as a simple parameter in the server side schema but it being a variable in the Android Studio definition of the query?
I just expected to receive the response back with no issues since it seems to work every other way. Even if I type in the query manually into my web browser I have no issues getting the right response, it's only when working with Apollo Client in G̶r̶a̶p̶h̶Q̶L̶ Android Studio that this issue pops up and I'm at a complete loss as to why. I appreciate any help people can offer. Thanks in advance.
Update: So looking around some more it looks like when sending a query via ApolloClient it sends the query as an object instead of as a JSON string. Now I'm thinking that's probably the cause of the 422 error. I've also read that allowing my GraphQL server to accept objects in addition to JSON strings is something I must enable. I'm not really sure how to go about that though, so does anyone with experience with Spring Boot have any advice on how I could go about doing that? Thanks.

About how to pass the ParseObject(Object) using Rest API(service) in Installation class in android?

I am sagar, i am trying to implement the Parse Push-Notification in android using REST API (Service), and i am almost got success in implement the Push-Notification in Xamarin-Android using REST API. But i got stuck with one part in sending the Data into REST service. I trying to pass the ParseObject in service, but the in parse table there is a need of Object,(). I have tried to pass the ParseObject as below:
JsonConvert.SerializeObject(ParseUser.CurrentUser)
It convert ParseObject into array and array is not accepted in table and ,i got failed to save it in table. because there i a need of object.
I need solution or suggestion from developer guys. Yours help will be appreciated. I am trying the below code to achieve the result.
public static void RegisterPush(string regristrationId)
{
if (regristrationId != null) {
string appID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string restID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string masterID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
var client = new RestClient ("https://api.parse.com");
var request = new RestRequest ("1/installations", RestSharp.Method.POST);
request.AddHeader ("Accept", "application/json");
request.AddHeader ("X-Parse-Application-Id", appID);
request.AddHeader ("X-Parse-REST-API-Key", restID);
request.Credentials = new NetworkCredential (appID, masterID);
request.Parameters.Clear ();
Console.Error.WriteLine ("ParseUser.CurrentUser-->"+ (ParseObject) ParseUser.CurrentUser);
//JsonConvert.SerializeObject(ParseUser.CurrentUser)
string strJSONContent = "{\"user\" :"+ JsonConvert.SerializeObject(ParseUser.CurrentUser)+",\"owner\":\"" + ParseUser.CurrentUser.ObjectId + "\",\"deviceType\":\"android\",\"GCMSenderId\":\"1234567890\",\"appName\":\"abcdefgh\",\"pushType\":\"gcm\",\"deviceToken\":\"" + regristrationId + "\"}";
Console.Error.WriteLine("json string-->"+ strJSONContent);
request.AddParameter ("application/json", strJSONContent, ParameterType.RequestBody);
client.ExecuteAsync (request, response => {
Console.Error.WriteLine ("response for android parse installation-->" + response.Content);
});
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
}
}`
Output:{"user" :[{"Key":"dealOffered","Value":4},{"Key":"dealRequested","Value":5},{"Key":"displayName","Value":"Cook"},{"Key":"email","Value":"lorenzo#gmail.com"},{"Key":"firstName","Value":"Lorenzo"},{"Key":"lastName","Value":"Cook"},{"Key":"mobileNumber","Value":9999999999.0},{"Key":"picture","Value":{"IsDirty":false,"Name":"tfss-afd25c29-6679-4843-842c-fe01f7fcf976-profile.jpg","MimeType":"image/jpeg","Url":"http://files.parsetfss.com/profile.jpg"}},{"Key":"provider","Value":"password"},{"Key":"userType","Value":"Merchant"},{"Key":"username","Value":"merchant#sailfish.com"},{"Key":"zipCode","Value":2342343}],"owner":"3cF1vHUXkW","deviceType":"android","GCMSenderId":"1234567890123","appName":"Sailfish","pushType":"gcm","deviceToken":"APA91bE3bsTIInQcoloOBE4kdLVVHVTRVtNyA1A788hYSC15wAVu8mUg-lwk7ZPk370rngrK7J6OoLmiM9HRr1CGPaBo6LCNrSUL7erBku4vepaFFkQzgqS6BcAemp"}
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
maven
I found the solution in , parse xamarin docs, in one query , the way is simple, but i little bit hard to found out.
The issue is with the data passing in json format in REST, to pass any pointer using REST API, use as below.
The solution is as below:
`{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"qYvzFzGAzc"
},
"owner":"qYvzFzGAzc",
"deviceType":"android",
"GCMSenderId":"123456789",
"appName":"NiceApp",
"pushType":"gcm",
"deviceToken":"APA91bFeM10jdrCS6fHqGGSkON17UjEJEfvJEmGpRM-d6hq3hQgDxKHbyrqAIxMnEGgbLEZf0E9AllHxiQQQCdEFiNMF1_A8q0n9tGpBE5NKhvS2ZGJ9PZ7585puWqz_1Z1EjSjOvgZ1LQo708DeL2KzA7EFJmdPAA"
}`
It looks like your column user is set up wrong. It should show as a Pointer<_User> not Pointer
If you load this class in your Data Browser, is the "user" key defined as a string, or a Pointer <_User>
This error seems to indicate that this is a string column, which is why the Parse.User object is not being accepted as a valid value. You might have tried setting a string on this key before, which in turn type-locked the "user" key as a string column.
Found it on the examples given on this page - https://www.parse.com/docs/rest
Have you check your REST API connection while passing ParseObject?
Because your error says:
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
Here "code":111This error code comes when server refuse for connection

Facebook Rest API working but auth issue with Android SDK

I am currently using thus url to test the Facebook graph API and get my page feed to display it in my application:
DOC: https://developers.facebook.com/docs/graph-api/reference/v2.2/page/feed
https://graph.facebook.com/PAGE_ID/feed?access_token=APP_ID|APP_TOKEN
(all ID obfuscated but I can share them and create a new app id needed)
So, this feed is working fine and gives me the JSON output I need:
{
data: [
{
id: "blahblah",
from: {
category: "Industrials",
name: "blahblah",
id: "blahblah"
},
message: "blahblahhttps://www.blahblah.com/",
picture: "https://fbexternal-a.akamaihd.net/safe_image.php?blahblah.jpg",
link: "https://www.blahblah.com/",
name: "Home",
caption: "blahblah",
description: "blahblah.",
icon: "https://fbstatic-a.akamaihd.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif",
privacy: {
value: ""
},
type: "link",
status_type: "shared_story",
created_time: "2015-01-21T12:30:37+0000",
updated_time: "2015-01-21T12:30:37+0000",
shares: {
count: 2
},
likes: {
Proble is that I want to use exactly the same feature, but instead of parsing JSON, I would like to use Facebook SDK.
This is my current code:
new Request(
null,
"/PAGE_ID/feed?access_token=APP_ID|APP_TOKEN",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.e("CVE","MESSAGE: "+response.getError().getErrorMessage());
}
}
).executeAsync();
But this method gives me some authentification issues.
I get the response: "Invalid OAuth access token signature"
Any idea what is wrong and if I have to use the HTTP request instead of Facebook SDK?
As #WizKid said above, NEVER put your app_token into a client app, that is a huge security hole. Only use user access tokens in your app. Alternatively, make the request server-side, and pass it on to your client app.
You're not using the Request methods properly. If you look at the documentation for the Request class (https://developers.facebook.com/docs/reference/android/current/class/Request/), you'll see that the second parameter is "graphPath", which should be only the "path" component of a URL. You are, however, including a query string as well, which is where things break. What you should do is something like this:
Bundle params = new Bundle();
params.putString("access_token", "YOUR_ACCESS_TOKEN");
new Request(
null,
"/PAGE_ID/feed",
params,
HttpMethod.GET,
...
Alternatively, you can also use the Session object instead (to get the user access token).

Categories

Resources