Node.js Paypal rest sdk - javascript

I'm new to Node.js and was deploying Paypal rest SDK, I'm stuck at this point, I want to pass a parameter from 'success' api that called by the paypal API, to the original API called by angular
//paypal
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': '',
'client_secret': ''
});
app.post('/pay-online', (req, res) => {
console.log('request came')
console.log(req.body.fare.toString())
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "localhost:3000/success",
"cancel_url": "localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": req.body.fare,
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": req.body.fare
},
"description": "This is the payment description."
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
res.send(payment.links);
}
});
});
var getSuccess = app.get('/success', (req, res) => {
var paymentId = req.query.paymentId;
var payerId = { payer_id: req.query.PayerID };
paypal.payment.execute(paymentId, payerId, function (error, payment) {
console.log(payment.state)
if (error) {
console.error(JSON.stringify(error));
} else {
if (payment.state == 'approved') {
console.log('payment completed successfully');
} else {
console.log('payment not successful');
}
}
});
});
My question that I need to pass (payment.state) to the page that called 'pay-online' API, how can I pass the parameter back to the page?

You can return a JSON object to the page which calls the 'pay-online' API as follows if you can get the state from "paypal.payment.create" method.
app.post('/pay-online', (req, res) => {
console.log('request came')
console.log(req.body.fare.toString())
var create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "localhost:3000/success",
"cancel_url": "localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": req.body.fare,
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": req.body.fare
},
"description": "This is the payment description."
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
res.send({
payment:payment.links,
state:payment.state . <----JSON Property
});
}
});
});
If you need to call the "paypal.payment.execute" method to get the payment state then you have to call "paypal.payment.execute" method inside the '/pay-online' method's success block.

Related

Issue while updating nested data createEntityAdapter RTK query

I am working on the chat that is utilising RTK Query with entity adapters. We created nested normalised createEntityAdapter . I want to update the message key from onCacheEntryAdded, but not able to update nested object. I'm attaching the query endpoint code along with sample response.
RTK Query Endpoint
endpoints: builder => ({
getMessages: builder.query({
query: ({ orderId, userId, channel }) => {
return {
url: `/messages?orderId=${orderId}&userId=${userId}`,
method: 'GET',
}
},
transformResponse(response, meta, arg) {
return messagesAdapter.setAll(messagesAdapter.getInitialState(), [
{
id: `${arg.orderId}-${arg.userId}`,
isTyping: false,
channel: arg.channel,
orderId: arg.orderId,
messages: messagesAdapter.addMany(
messagesAdapter.getInitialState(),
response,
),
},
])
},
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved, cacheData },
) {
try {
await cacheDataLoaded
updateCachedData(draft => {
messagesAdapter.updateOne(draft, {
id: '62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72',
changes: {
messages: messagesAdapter.updateOne(
messagesAdapter.getInitialState(),
{
id: '62da7221bc0eb3a259fc2256',
changes: {
message: 'updated message',
},
},
),
},
})
})
} catch {
// no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,
// in which case `cacheDataLoaded` will throw
}
await cacheEntryRemoved
},
providesTags: (result, error, arg) => {
console.log('providesTags', result, error, arg)
return ['chat']
},
}),
}),
Sample response
{
"ids": [
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72"
],
"entities": {
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72": {
"id": "62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72",
"isTyping": false,
"channel": "62d7d9266599a9f0c3bcdaba",
"orderId": "62d529f60be7549be1f53df3",
"messages": {
"ids": [
"62da7221bc0eb3a259fc2256",
"62da724dbc0eb3a259fc2260",
"62da75559f7a23f89a0958d4",
"62da94e59f7a23f89a0958ed"
],
"entities": {
"62da7221bc0eb3a259fc2256": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "dsds",
"sentAt": "2022-07-22T09:47:13.000Z",
"id": "62da7221bc0eb3a259fc2256"
},
"62da724dbc0eb3a259fc2260": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello nm",
"sentAt": "2022-07-22T09:47:57.000Z",
"id": "62da724dbc0eb3a259fc2260"
},
"62da75559f7a23f89a0958d4": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "b",
"sentAt": "2022-07-22T10:00:53.000Z",
"id": "62da75559f7a23f89a0958d4"
},
"62da94e59f7a23f89a0958ed": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello there",
"sentAt": "2022-07-22T12:15:31.000Z",
"id": "62da94e59f7a23f89a0958ed"
}
}
}
}
}
}

NodeJS hendt/ebay-api / getOrders / Error - Insufficient permissions to fulfill the request

So I am using the hendt/ebay-api library but having no success with the getOrders call.
Here's the auth scopes I'm using when setting the ORIGINAL User access token...:
eBay.auth.oAuth2.setScope([
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
]);
Here's my code (ExpressJS backend controller method...):
exports.getOrders = async (req, res) => {
let _id = req.params.userId; // user's _id
let token = await refreshEbayToken(_id, eBay)
console.log(`token...`, token) // not an array! It's an object!
// set OAuth2 eBay credentials
eBay.auth.oAuth2.setCredentials(token.access_token);
try {
let result = await eBay.sell.fulfillment.getOrders({
filter: 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
limit: 5
})
console.log(`Got a result...`, result)
res.json(result)
} catch (e) {
console.log(`Got an error in getOrders...`, e)
res.status(400).json( { error: e } )
}
}
Here's the error I get:
{
"meta": {
"errors": [
{
"errorId": 1100,
"domain": "ACCESS",
"category": "REQUEST",
"message": "Access denied",
"longMessage": "Insufficient permissions to fulfill the request."
}
]
},
"name": "EBayAccessDenied"
}
Even freshly minted User access tokens through those scopes get this error.
According to the ebay docs on getOrders, these are the required auth scopes for this call:
https://api.ebay.com/oauth/api_scope/sell.fulfillment
https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly
Upon further investigation, I found I am certainly using those scopes in the response (below is a snippet of the scopes grabbed from the larger ebay error)...
...%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.fulfillment.readonly%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.fulfillment%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.analytics.readonly%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.finances%20...
As shown above, I am clearly using the sell.fulfillment and sell.fulfillment.readonly scopes so I do not understand what is the issue.
What do you think could be the issue?
So I am using the library but having no success with the getOrders call.
Here's the auth scopes I'm using when setting the ORIGINAL User access token
https://gist.github.com/mudassaralichouhan/d952b464b2907c7f833c87c05152eb76
I finally got it working.
Here is an example of what I receive now:
{
"sales": [
{
"orderId": "xxxxxxxxx",
"legacyOrderId": "xxxxxxxxx-xxxxxxxxx",
"creationDate": "2022-03-09T23:10:36.000Z",
"lastModifiedDate": "2022-03-18T15:51:04.000Z",
"orderFulfillmentStatus": "FULFILLED",
"orderPaymentStatus": "PAID",
"sellerId": "xxxx",
"buyer": {
"username": "xxxxx",
"taxAddress": {
"stateOrProvince": "xx",
"postalCode": "xxxxxxxx",
"countryCode": "xx"
}
},
"pricingSummary": {
"priceSubtotal": {
"value": "xxxxx",
"currency": "USD"
},
"deliveryCost": {
"value": "0.0",
"currency": "USD"
},
"total": {
"value": "xxxxx",
"currency": "USD"
}
},
"cancelStatus": {
"cancelState": "NONE_REQUESTED",
"cancelRequests": []
},
"paymentSummary": {
"totalDueSeller": {
"value": "xxxxx",
"currency": "USD"
},
"refunds": [],
"payments": [
{
"paymentMethod": "EBAY",
"paymentReferenceId": "xxxxxx",
"paymentDate": "2022-03-09T23:15:33.109Z",
"amount": {
"value": "xxxxxxxx",
"currency": "USD"
},
"paymentStatus": "PAID"
}
]
},
"fulfillmentStartInstructions": [
{
"fulfillmentInstructionsType": "SHIP_TO",
"minEstimatedDeliveryDate": "2022-03-14T07:00:00.000Z",
"maxEstimatedDeliveryDate": "2022-03-19T07:00:00.000Z",
"ebaySupportedFulfillment": false,
"shippingStep": {
"shipTo": {
"fullName": "xxxxxxxxxx",
"contactAddress": {
"addressLine1": "xxxxxxxxxxx",
"city": "xxxxxxxxxx",
"stateOrProvince": "xx",
"postalCode": "xxxxxxxxx",
"countryCode": "US"
},
"primaryPhone": {
"phoneNumber": "xxxxxxxxxxxxx"
},
"email": "xxxxxxxxxxxx#members.ebay.com"
},
"shippingServiceCode": "ShippingMethodStandard"
}
}
],
"fulfillmentHrefs": [
"https://api.ebay.com/sell/fulfillment/v1/order/xxxxxxxxxxx/shipping_fulfillment/xxxxxxxxxx"
],
"lineItems": [
{
"lineItemId": "xxxxxxxxxx",
"legacyItemId": "xxxxxxxxxx",
"legacyVariationId": "xxxxxxxxxx",
"sku": "xxxxxxxxxx",
"title": "xxxxxxxxxx",
"lineItemCost": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"quantity": 1,
"soldFormat": "FIXED_PRICE",
"listingMarketplaceId": "EBAY_US",
"purchaseMarketplaceId": "EBAY_US",
"lineItemFulfillmentStatus": "FULFILLED",
"total": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"deliveryCost": {
"shippingCost": {
"value": "0.0",
"currency": "USD"
}
},
"appliedPromotions": [],
"taxes": [],
"ebayCollectAndRemitTaxes": [
{
"taxType": "STATE_SALES_TAX",
"amount": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"collectionMethod": "NET"
}
],
"properties": {
"buyerProtection": true
},
"lineItemFulfillmentInstructions": {
"minEstimatedDeliveryDate": "2022-03-14T07:00:00.000Z",
"maxEstimatedDeliveryDate": "2022-03-19T07:00:00.000Z",
"shipByDate": "2022-03-14T06:59:59.000Z",
"guaranteedDelivery": false
},
"itemLocation": {
"location": "xxxxxxxxxx",
"countryCode": "US",
"postalCode": "xxxxxxxxxx"
}
}
],
"ebayCollectAndRemitTax": true,
"salesRecordReference": "xxxxxxxxxx",
"totalFeeBasisAmount": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"totalMarketplaceFee": {
"value": "xxxxxxxxxx",
"currency": "USD"
}
}
]
}
Here are my scopes:
eBay.auth.oAuth2.setScope([
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
]);
Here is the code getting it right ( express.js )...
exports.getOrders = async (req, res) => { // https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetOrders.html
let _id = req.params.userId; // user's _id
let a = {}
a._id = _id
a.userDoc = await User.findById( { _id: a._id } )
eBay.auth.oAuth2.setCredentials( a.userDoc.token[ 0 ] ) // set OAuth2 eBay credentials
try
{
a.result = await eBay.trading.getOrders({
filter: 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
limit: 5
})
console.log(`Got a result...`, a.result)
} catch ( e ) {
}
}
I send in the mongodb user _id as request params and use that to pull out their user token, which is passed into eBay.auth.oAuth2.setCredentials( a.userDoc.token[ 0 ] ) and allows the call to actually be made... eBay.trading.getOrders
I hope this helps someone out there. I remember being unable to make this call for months.

How can find in object at object of array in express

For each post I have this structure:
{
"_id": "5dfd3b918937d40b98afd3f8",
"user": "5deea38cfc84f42590e01942",
"title": "test",
"description": "description test",
"category":
{
"0": "1",
"1": "101"
},
"phone": "+1",
"country": "USA",
"city": "NY",
"options": {
"transaction_type": ""
},
"date": "2019-12-20T21:22:25.940Z",
}
In express I using bottom code for find posts by category id but not working what I should to do?
router.get("/category/:category", async (req, res) => {
try {
const posts = await Post.find({
category: { $all: req.params.category }
}).sort({ date: -1 });
if (!posts) {
return res.status(404).json({ msg: "Ads not found" });
}
const resultPosts = posts.slice(req.query.start, req.query.count);
res.json(resultPosts);
} catch (err) {
console.error(err.message);
if (err.kind === "ObjectId") {
return res.status(404).json({ msg: "Ads not found" });
}
res.status(500).send("Server Error!");
}
});

How to get rid of validation error with paypal-rest-sdk?

I am using the paypal-rest-sdk to practice using the paypal checkout. I've set up a small test and whenever I click submit in my form I get a "localhost refused to connect" error in Chrome. I've turned off my proxy and cleared my history and cache. I've also double checked my client and secret keys from Paypal. I'm not sure what I am doing wrong. Here's my code:
app.js:
const express = require('express');
const ejs = require('ejs');
const paypal = require('paypal-rest-sdk');
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'xxxxxxxx',
'client_secret': 'xxxxxxx'
});
const app = express();
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index'));
// create the json obj for the transaction with the order details
app.post('/pay', (req, res) => {
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "Red Sox Hat",
"sku": "001",
"price": "25.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "1.00"
},
"description": "This is the payment description."
}]
};
// pass in the object we've created and now create the actual payment
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
console.log(error);
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
res.send('test');
}
});
});
app.listen(3000, () => console.log('Server Started'));
here is what the terminal outputs from the error:
response:
{ name: 'VALIDATION_ERROR',
details: [ [Object] ],
message: 'Invalid request - see details',
information_link: 'https://developer.paypal.com/docs/api/payments/#errors',
debug_id: 'fb61fe9c14b46',
httpStatusCode: 400 },
httpStatusCode: 400 }
I expect the message of 'test' to appear on the screen when the pay route is rendered so that I know the connection works, but so far all I've gotten is "ERR_CONNECTION_REFUSED" from Chrome. Please let me know what I am doing wrong. Thanks in advance.
Your payment JSON is missing required information.
Please see an valid payment JSON below:
{
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://www.example.com/return_url",
"cancel_url": "http://www.example.com.br/cancel"
},
"transactions": [
{
"amount": {
"currency": "USD",
"total": "200.00",
"details": {
"shipping": "10.00",
"subtotal": "190.00"
}
},
"item_list": {
"items": [
{
"name": "Foto 1",
"currency": "USD",
"sku": "123",
"quantity": "1",
"price": "190.00"
}
]
},
"description": "Payment description"
}
]
}

iteration on Datasource in Angular

I want to make a function which iterates through an array of object and set the property status to false.
The array of obj is a datasource on angular table.
this.lightService.getLamp()
.subscribe(
(response) => {
this.lampData = response;
this.dataSource.data = response;
},
(error) => {
console.log('error ' + error);
}
The Data source
{
"id": 1,
"group" : 1,
"name": "Lamp 1",
"connected": " Not Connected",
"status": true,
"address": "1",
"channel": "All",
"temperature": 3200,
"error": false,
"errorMessage": "Not Working at this moment"
},
{
"id": 2,
"group" : 2,
"name": "Lamp 2",
"connected": "Connected",
"status": true,
"address": "2",
"channel": "All",
"temperature": 6500,
"error": false,
"errorMessage": "Not Working at this moment"
},
{
.....
}
]
You can use the .map operator for iterating through all the objects in an array. I suppose the below code should work for you.
this.lightService.getLamp()
.subscribe(
(response) => {
this.lampData = response;
this.dataSource.data = response;
this.dataSource.data.map(item => {
item.status = false
})
},
(error) => {
console.log('error ' + error);
}

Categories

Resources