Telegraf: "replyWithInvoice" isn't available for "callback_query::" - node.js

I have a callback_query when users hit on a purchase button. The callback_query is to send an invoice to the user, but it is throwing the above error.
bot.on('callback_query', (ctx) => {
let data = ctx.callbackQuery.data
if (data.includes('purchase') == true) {
return handlePurchase(ctx)
}
})
function handlePurchase(ctx) {
let data = ctx.callbackQuery.data
let itemId = data.split(':')[1]
let invoice = {
chat_id: ctx.callbackQuery.from.id,
title: "Title",
description: "Description",
payload: itemId.toString(),
provider_token: stripeToken,
start_parameter: itemId.toString(),
currency: "USD",
need_phone_number: true,
need_shipping_address: true,
photo_url: the_image_url,
prices: [{
label: "Item",
amount: 1000
}]
}
return ctx.replyWithInvoice(invoice)
}
I also attempted to use ctx.telegram.sendInvoice(invoice) instead but the bot did not send an invoice to the user, ie the bot did not respond at all.

Related

paypal check out node js error UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'price' of undefined when i run my code

I have the following code it suppose to send the data to pay pal to process the payment but it keepsgeting this TypeError: Cannot read property 'price' of undefined i have gone through the code but i think the error is occuring "storeItems.get(item.id).price" when i try to get the "items id" for some reson thwe value is nt being seen
this is my request body contains the following array
{"items":[
{"id":"1", "quantity":1},
{"id":"2", "quantity":2},
{"id":"3", "quantity":3},
{"id":"4", "quantity":4}
]}
app.post("/create-order", async (req, res) => {
const request = new paypal.orders.OrdersCreateRequest()
const total = req.body.items.reduce((sum, item) => {
return sum + storeItems.get(item.id).price * item.quantity
}, 0)
console.log(total);
request.prefer("return=representation")
request.requestBody({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "USD",
value: total,
breakdown: {
item_total: {
currency_code: "USD",
value: total,
},
},
},
items: req.body.items.map(item => {
const storeItem = storeItems.get(item.id)
return {
name: storeItem.name,
unit_amount: {
currency_code: "USD",
value: storeItem.price,
},
quantity: item.quantity,
}
}),
},
],
})
const order = await paypalClient.execute(request)
})
The error means that storeItems.get(item.id) in the total function is undefined.
From your comment, storeItems is defined like:
const storeItems = new Map([
[1, { price: 100, name: "Learn React Today" }],
[2, { price: 200, name: "Learn CSS Today" }],
])
So the issue must come from the item. Either it does not have an id property, or it is undefined, or its id property does not match any entry in your map.

How do I update a nested list data in dynamodb using serverless stack?

I have a dynamoDB table that has an Item that includes a user and a List of plans. It looks like this:
Item:
{
user: 'abc123',
plans: [
{
id: 1,
name: 'movies',
category: 'category',
price: 200,
},
{
id: 2,
name: 'fishing',
category: 'category2',
price: 400,
}
]
}
Now, I want to update only id:2's object(name, category, price) in the List. So I wrote the handler below. And there is an error edit error ValidationException: The document path provided in the update expression is invalid for update in CloudWatch.
export const processAddPlan = async (event:APIGatewayEvent) => {
const data = JSON.parse(event.body)
const { store, id } = event.queryStringParameters
const params = {
TableName: usersTable,
Key: {
store: store,
id: id,
},
UpdateExpression: 'SET #pl[1] = :plans',
ExpressionAttributeNames: {
'#pl' : 'plans',
},
ExpressionAttributeValues: {
':plans': [
{
'name': data.planName,
'category': data.planCategory,
'price': data.planPrice,
},
],
},
ReturnValues: 'UPDATED_NEW',
}
log.info('params', params)
await dynamoDb.update(params).catch(e => log.info('edit error', e))
return success('edit plan succeeded')
}
I set query params and I tested(send) by postman like this.
{
"plans":[
{"planName":"ga2new",
"planCategory": "ttnew",
"planPrice": 5675
}
]
}
You need to use SET.
SET pl[1] = :plans
As the docs show here:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.SET.AddingListElements
The docs for ADD say
The ADD action supports only number and set data types.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.ADD

How To Sort Firebase Joined Query

I'm New To firebase, i have a query
const posts = database.child('posts');
const user = database.child('user');
posts.orderByChild("id").on('child_added', snap => {
let user_id = snap.val().user_id;
let userRef = database.child('user/' + snap.val().user_id)
userRef.on('value', userSnap => {
console.log(userSnap.val().name)
let content = snap.val().content;
let date_posted = snap.val().date_posted;
let id = snap.val().id;
let title = snap.val().title;
let user_id = snap.val().user_id;
let user_Name = userSnap.val().name;
a.push({
"id": id,
"title": title,
"date_posted": date_posted,
"content": content,
"user_Name": user_Name,
"user_id": user_id
})
});
});
before entering UserRef Query, The posts are well sorted With The id,
however after the 2nd query, it's no longer sorted, How Can i make them sorted even after the 2nd query
this is the db structure
!:
i want the output to be like this
{
id: 1,
title: 'My First Post',
date_posted: '2018-05-02 19:40:02',
content: 'This is my firstpost!',
user_Name: 'Abdelrahman',
user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
},
{
id: 2,
title: 'My SecondPost',
date_posted: '2018-05-02 19:41:02',
content: 'This is my Second post!',
user_Name: 'Abdelrahman',
user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
},
{
id: 3,
title: 'test Title',
date_posted: '2021-01-06 08:48:01',
content: 'test Content',
user_Name: 'Abdelrahman',
user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
},
{
id: 4,
title: 'test Title2',
date_posted: '2021-01-06 08:49:42',
content: 'test Content2',
user_Name: 'Abdelrahman',
user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
},
{
id: 5,
title: 'test 3',
date_posted: '2021-01-06 08:54:14',
content: 'COntent 3',
user_Name: 'Abdelrahman',
user_id: '8721da2c-0028-430f-a995-0d03c8abb393'
}
but the output i see is not sorted at all
Usually you store the token as state in vuex. In your method you commit a mutation to set the token state, something like:
this.$store.commit('SET_TOKEN', res.data)
In the store you will have
state: {
token: '',
},
mutations: {
SET_TOKEN(state, payload) {
state.token = payload.token
}
This is just an example to be adjusted depending on response you get.
If you need to persist the state you should use also vuex persisted state

Paypal window not showing multiple items

I'm creating my own cart and then using Paypal smart button for the payment in Angular.
For multiple items to handle, I'm uing items array in createOrder method at the backend in Express.
function arrayOfItems() {
art_details.forEach((item, index) => {
let sku = item.message;
let currency = priceDetails.collPriceL[index];
let tax = priceDetails.taxAmtL[index];
let quantity = item.quantity;
let items = [
{
name: "Collection",
sku: sku,
description: '' + item.collid,
unit_amount: { currency_code: "CAD", value: "" + currency },
tax: { currency_code: "CAD", value: "" + tax },
quantity: quantity,
},
];
return items;
});
}
I'm now using arrayOfItems() as items in createOrder:
const request = new checkoutNodeJssdk.orders.OrdersCreateRequest();
request.prefer("return=representation");
request.requestBody({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "CAD",
value: ...,
breakdown: {
...
},
},
soft_descriptor: orderkey,
items: arrayOfItems(),
shipping: {
...
},
},
],
});
Suppose I'm creating order for 2 items. art_details contains array of items I need to purchase. My order is creating successfully but the Paypal window doesn't show the items in right side. (it should appear as a dropdown of items).
What am I missing here?
Thanks

Must provide source or customer stripe live mode

this is my first time using stripe and I am getting an error Must provide source or customer. once I went live. In the test mode I used "tok_mastercard" as my source but clearly when I went live it isn't valid. What am I missing here please help.
This is my POST request in the backend
stripe.charges
.create({
amount: req.renter.rent * 100,
currency: "usd",
source: req.body.token,
application_fee_amount: req.renter.rent * 0.05 * 100,
transfer_data: {
//the destination needs to not be hard coded it needs to
//come from what property the renter is in
destination: req.renter.stripeConnectId,
// destination: "acct_1GOCMqDfw1BzXvj0",
},
})
.then((charge) => {
console.log(req.renter);
res.send(charge);
})
.catch((err) => {
console.log(err);
});
});
this is my two functions in the frontend using react-native and node
handleCardPayPress = async () => {
try {
this.setState({ loading: true, token: null });
const token = await stripe.paymentRequestWithCardForm({
// Only iOS support this options
smsAutofillDisabled: true,
requiredBillingAddressFields: "full",
prefilledInformation: {
billingAddress: {
name: "",
line1: "",
line2: "",
city: "",
state: "",
country: "US",
postalCode: "",
email: "",
},
},
});
this.setState({ loading: false, token });
} catch (error) {
this.setState({ loading: false });
}
};
makePayment = async () => {
try {
//Mate the payment
const response = await unitApi.post("/payments", {
data: {
amount: this.state.renter.rent,
currency: "usd",
token: this.state.token,
},
});
Alert.alert("Success!", `Confirmation ID: ${response.data.id}`, [
{ text: "Done" },
]);
console.log(response.data);
// navigate("Home");
} catch (err) {
//failiur and showing the error message
console.log(err);
Alert.alert("Failed!", "Card declined.", [{ text: "Declined" }]);
}
};
Odds are pretty good that this.state.token doesn't contain what you think it does in the unitApi.post() function call; I'd recommend logging that and seeing if that helps, and also logging req.body.token server-side.

Resources