Using Paypal REST api in .net - asp.net-core

I am trying to implement PayPal REST API with my .net application. For this I am using the sandbox accounts. By referring the demos/documents below code is written which will first create the order and then will make the payment for the same order.
However, my issue is I am not able to grab the order ID. Though I am getting in res.json() from below code. I need to get the order ID, set it to some variable and use it in the subsequent requests. This below code I have got from the demo link and made some changes as per my requirement.
Also in the OnApprove block I am not getting the data.id.
<div id="paypal-button-container"> </div>
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// Set up the transaction
createOrder: function (data, actions) {
return fetch('https://api.sandbox.paypal.com/v2/checkout/orders', {
method: 'post',
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer <My Access Token>'
},
body: JSON.stringify({
"intent": "CAPTURE",
"purchase_units": [
{
"amount": {
"currency_code": "USD",
"value": "100.00"
}
}
]
})
}).then(function (res) {
return res.json();
}).then(function (data) {
return data.id;
});
},
// Finalize the transaction
onApprove: function (data, actions) {
return fetch('https://api.sandbox.paypal.com/v2/checkout/orders/' + data.id + '/capture/', {
method: 'post',
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer <My Access Token>'
},
}).then(function (res) {
return res.json();
}).then(function (details) {
console.log(details);
// Show a success message to the buyer
alert('Transaction completed');
});
}
}).render('#paypal-button-container');
</script>
Also, Can I execute my own APIs from the PayPal buttons ?
Any help on this appreciated !

Your code seems perfect(almost). You just need to keep in mind the scope of the variables here. As the 'data' variable is restricted to the 'then' block, you will need to create a new variable to hold the value of 'data.id' and use it in the onApprove block.
I've added a new variable called 'orderID' in the code below and this seems to be working.
<script>
var orderID; //Declared a variable
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// Set up the transaction
createOrder: function (data, actions) {
return fetch('https://api.sandbox.paypal.com/v2/checkout/orders', {
method: 'post',
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer <My Access Token>'
},
body: JSON.stringify({
"intent": "CAPTURE",
"purchase_units": [
{
"amount": {
"currency_code": "USD",
"value": "100.00"
}
}
]
})
}).then(function (res) {
return res.json();
}).then(function (data) {
orderID = data.id; //storing the id in our variable
return data.id;
});
},
// Finalize the transaction
onApprove: function (data, actions) {
//using the id stored in our variable
return fetch('https://api.sandbox.paypal.com/v2/checkout/orders/' + orderID + '/capture/', {
method: 'post',
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer <My Access Token>'
},
}).then(function (res) {
return res.json();
}).then(function (details) {
console.log(details);
// Show a success message to the buyer
alert('Transaction completed');
});
}
}).render('#paypal-button-container');
</script>
The implementation you are doing is ideally used for cases when there is a server side component involved, and the API call to the PayPal servers is done via the server.
If you implementation does not require a server side then I will highly recommend to follow the Smart Payment Buttons implementation - https://developer.paypal.com/docs/checkout/integrate/#

Related

How to get response with axios api with "GET" method in react native

Here is my code:
axios({
method: "GET",
url: "http://112.196.108.244:9002/api/survey/question/get-question/not-answered/?surveyId=",
headers: {
"content-type": "application/json",
Authorization: `Bearer token-key`,
},
body: {
id: "68367859",
isMandatory: "false",
paginationFilter: { limit: 10, offset: 0, order: "DESC" },
filterInput: {
locationIds: ["1", "4011403", "4012144"],
categoryIds: [
"twoSubCategories/7898496",
"domains/7895290",
"subCategories/7896491",
],
},
},
})
.then((response) => {
console.log("response", response);
})
.catch((error) => {
console.log("error", error.response.data);
});
this code gives me error:
The error in console is-
details: "uri=/api/survey/question/get-question/not-answered/"
message: "document key is not valid."
status: 400
You're passing the id in the body. There are two problems at play here:
GET requests shouldn't use a body as part of the request. Check this answer.
What you want to do is pass the id (Which I assume is the survey id) as a query parameter. Something like this should work:
axios({
method: 'GET',
url: 'http://112.196.108.244:9002/api/survey/question/get-question/not-answered/',
headers: {
'content-type': 'application/json',
Authorization: "Bearer token-key"
},
params: {
surveyId: "68367859"
}
})
Add other params as necessary.

How to run GraphQL request in Pre-Request Script section in postman?

I want to run a query before the actual request runs and get a value from the pre-request response and set it in a collection variable.
I have a problem running the following as I used to do it while testing REST APIs.
This is what I tried to do
const getUserBeforeUpdate = {
url: pm.environment.get("base-url"),
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.environment.get("token")}`},
body: JSON.stringify({query: '{ user { profile {id} } }'})
};
pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);
// set collection variable from the response
});
but I get a console error stating
There was an error in evaluating the Pre-request Script: Error: Unexpected token u in JSON at position 0
What's the right way to chain requests in graphql?
Collection variable are accessible via collectionVariables. This should work for you:
const getUserBeforeUpdate = {
url: pm.collectionVariables.get("base-url"),
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.collectionVariables.get("token")}`},
body: JSON.stringify({query: '{ user { profile {id} } }'})
};
pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);
// set collection variable from the response
});
I was able to fix this by changing the url value to the actual url directly as a string. I'm not sure why getting the variable from environment didn't work yet.
I don't have the ability to run you request but would this work?
const getUserBeforeUpdate = {
url: `${pm.environment.get("base-url")}`,
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.environment.get("token")}`},
body: JSON.stringify({
query: 'query { user { profile { id } } }'
})
};
pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);
// set collection variable from the response
});

Vuejs: axios; Passing custom header in POST method

We are making an axios POST call from VueJs, need to pass a custom header. The way it is coded now, the custom header is not getting passed to the server script, other headers are getting passed. Please let me know what I might be doing wrong. Appreciate your help.
axios({
method: 'post',
url: urltocall,
data: strjson,
config: {
headers: {
'Access-Control-Allow-Origin': 'http://localhost:1337',
'Accept': 'application/json',
'Content-Type': 'application/json',
'username': 'test1'
}
}
})
.then(function (response) {
}
The headers object should not be put into a "config" object.
It's just...
axios({
method: 'post',
url: urltocall,
{
headers: {
....
Try doing it like this:
axios
.post(urltocall, myDataAsJSON, {
headers: {
"Access-Control-Allow-Origin": "http://localhost:1337",
"Accept": "application/json",
"Content-Type": "application/json",
"username": "test1"
}
})
.then(response => {
console.log("Success: " + response.data);
})
.catch(error => {
console.log("Error: " + error.response.data);
});
By the way, based on your 'Content-Type': 'application/json',, I know you're trying to send a JSON object, but where/what is this object?
Also, refer to the Full documentation for more information.

update_client_config_error error in VueStrorefront + vsf-payment-paypal

I'm a beginner in Vue Storefront. I'm trying to integrate Paypal to Vue Storefront. I have followed all steps in read me of this package (vsf-payment-paypal). But I'm stuck on this following error for two days,
update_client_config_error
Uncaught TypeError: Cannot read property \'find\' of undefined at VueComponent.grandTotal (http://localhost:3000/dist/vsf-checkout.js:1446:25)
Any idea how to fix this issue? Please help.
I'm Dealing with same issues for Hours in NodeJS and i was able to fix it the issue is on Your Json not in PayPal configurations.
let order;
try
{
order = await client.execute(request);
let response = {
statusCode: '200',
body: JSON.stringify({ orderID: order.result.id }),
headers: {
'Content-Type': 'application/json',
}
};
return JSON.stringify({ orderID: order.result.id });
}
catch (err)
{
console.error(err);
let response = {
statusCode: '500',
body: JSON.stringify({ error: 'Something Went Wrong While Creating Order..!' }),
headers: {
'Content-Type': 'application/json',
}
};
return response;
}
this is how i modify my return on nodejs server side
body: JSON.stringify({ orderID: order.result.id })
and this is my Create Order function
createOrder: function() {
return fetch('http://localhost:3000/PayPal/Pay', {
method: 'post',
headers: {
'content-type': 'application/json'
}
}).then(function(res) {
return res.json();
}).then(function(data) {
console.log("data.orderID" +data);
return data.orderID; // Use the same key name for order ID on the client and server
});
}
}).render('#paypal-button-container')});
Sorry i Don't know anything about Vue so i can't help with that. but hope this will help you ..! Good luck

HttpClient or Http POST with header request not hitting to the server

I'm trying to issue an http request to validate user and in response i need to get token issued by the server.
this ajax call working fine
$.ajax({
url: '/token',
'data': JSON.stringify({ Id: "test", Password: "test" }),
'type': 'POST',
'processData': false,
'contentType': 'application/json',
success: function (response) {
console.log("token =" + response);
},
});
But i need it in angular so i tried below two methods but none of them worked.
1st
let header = new Headers({ 'Content-Type': 'application/json', 'processData': false});
let options = new RequestOptions({ headers: header });
this.http.post('/token', JSON.stringify({ Id: "test", Password: "test" }), options)
.map(response => {
debugger;
console.log("token =" + response);
});
2nd
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response'
});
what is wrong with them.
I am using Dotnet Core 2.1 and angular 5
Please help me to solve this issue.
Your methods are observables.
In order to send the request and get the result, you need to subscribe to them.
This is an example of the 2nd method.
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}).subscribe(response => {
console.log("token =" + response);
});