i am using push notification with local notification.. i have to set channel id in my payload..
here is my payload
i am not sure if this is payload for both andriod and ios. please help me out with correct payload.
thanks
exports.chatFunctions = functions.firestore.document("chat/{chatId}/Messages/{messagesId}").onCreate(async (snapshot, context) => {
if (!snapshot.exists) {
console.log('No Device');
}
const chatDatas = snapshot.data();
const messageTo = chatDatas['idTo'];
const deviceTokenuUser1 = await admin.firestore().collection('users').doc(messageTo).get();
const user1name = deviceTokenuUser1.data()['name'];
const user1Url = deviceTokenuUser1.data()['profilePictureUrl'];
let payload = {
notification: {
title: `${user1name}`,
body: `${chatDatas['content']}`,
},
data: {
key: 'chat',
id: `${messageTo}`,
click_action: "FLUTTER_NOTIFICATION_CLICK"
},
android: {
priority: "high",
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
token: deviceTokenuUser1.data()['tokens'],
};
try {
await admin.messaging().send(payload);
console.log("Firebase chat Messaging Successfully");
} catch (err) {
console.log("error from chat messaging " + err);
}
You can add channel id like this:
let payload = {
// ...
android: {
priority: "high",
notification: {
channelId: "yourchannelid"
}
}
// ...
}
Related
I'm having an issue connecting to a GraphQL endpoint using Web-sockets.
The issues are noted in the comments. I cannot get this working. It works on the browser (separate test application) so the server is fine.
IOWebSocketChannel? _channel;
StreamSubscription? _getSubscription;
connectToWebsocket(BuildContext context) {
// Nothing to listen to. Auth users only.
final auth = authProviderRead(context);
if (auth.modelUser == null) {
return;
}
_channel?.sink.close();
_getSubscription?.cancel();
final headers = {
"Authorization": auth.jwt ?? "",
"Content-Type": "application/json",
};
_channel = IOWebSocketChannel.connect(
Uri.parse(getWebStockUrl()),
headers: headers,
protocols: ["graphql-ws"],
);
// Fails: Just fires "onDone"
// _channel?.sink.add(jsonEncode({"data": subscriptionQuery}));
// Fails with {"type":"connection_error","payload":{"message":"Cannot read properties of undefined (reading 'Authorization')"}}
// _channel?.sink.add(json.encode({"type": "connection_init"}));
// Fails with {"type":"error","payload":{"message":"Invalid message type!"}}
// _channel?.sink.add(jsonEncode(
// {
// "type": "data",
// "query": subscriptionQuery,
// },
// ));
_getSubscription = _channel!.stream.listen((message) {
// Is never fired?
if (kDebugMode) {
print("Got live message");
print(message);
}
// channel!.sink.add('received!');
// channel!.sink.close();
})
..onData((data) {
if (kDebugMode) {
print("onData - WebSocket");
print(data);
}
})
..onDone(() {
if (kDebugMode) {
print("onDone - WebSocket");
}
})
..onError((e) {
if (kDebugMode) {
print("onError - WebSocket");
print(e);
}
});
}
const subscriptionQuery = r'''
subscription Subscription {
gotChatMessage {
messageResults {
message {
markdown
}
}
}
}
''';
I figure it out, there are some additional things that it requires.
From https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/message-types.ts
_channel?.sink.add(jsonEncode({
"type": "connection_init",
"payload": {"Authorization": auth.jwt}
}));
_channel?.sink.add(jsonEncode({
"type": "start",
"payload": {"query": subscriptionQuery}
}));
i have this payload below that send push from firebase function. the payload send notification successful to Android. now i am confused about the iOS.
my Question is that:
will this also send to iOs because i can see that there is no alert in the payload in apsn.
i fellow the documentation in this site which they did not give ios payload.
when i make a research on iOs payload i can see something like this
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
but in the documentation i cant found where they give alert
exports.chatFunctions = functions.firestore.document("chat/{chatId}/Messages/{messagesId}").onCreate(async (snapshot, context) => {
if (!snapshot.exists) {
console.log('No Device');
}
const chatDatas = snapshot.data();
const messageTo = chatDatas['idTo'];
const deviceTokenuUser1 = await admin.firestore().collection('users').doc(messageTo).get();
const user1name = deviceTokenuUser1.data()['name'];
const user1Url = deviceTokenuUser1.data()['profilePictureUrl'];
let payload = {
notification: {
title: `${user1name}`,
body: `${chatDatas['content']}`,
},
data: {
key: 'chat',
id: `${messageTo}`,
click_action: "FLUTTER_NOTIFICATION_CLICK"
},
android: {
priority: "high",
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
token: deviceTokenuUser1.data()['tokens'],
};
try {
await admin.messaging().send(payload);
console.log("Firebase chat Messaging Successfully");
} catch (err) {
console.log("error from chat messaging " + err);
}
I am trying to implement a PUT request to the https://crudcrud.com/ REST API.
I have a list of users and when I click an update button, I would like to show a modal and allow the user to update any of the fields (name, email, image URL). The main concern is that I am struggling with how to format the PUT request.
This is my current solution
// template (UserCrud.vue)
<button #click="update(user._id)">Update</button>
// script
components: { Create },
setup() {
const state = reactive({
users: [],
})
onMounted(async () => {
const { data } = await axios.get(`/users`)
state.users = data
})
async function update(id) {
await axios.put(`/users/${id}`)
state.users = ???
}
return { state, destroy, addUser }
Here is some sample data:
[
{
"_id": "6012303e37711c03e87363b7",
"name": "Tyler Morales",
"email": "moratyle#gmail.com",
"avatar": "HTTP://linkURL.com
},
]
For reference, this is how I create a new user using the POST method:
export default {
components: { Modal },
emits: ['new-user-added'],
setup(_, { emit }) {
const isModalOpen = ref(false)
const state = reactive({
form: {
name: '',
email: '',
avatar: '',
},
})
async function submit() {
const { data } = await axios.post('/users', state.form)
emit('new-user-added', data)
state.form.email = ''
state.form.name = ''
state.form.avatar = ''
isModalOpen.value = false
}
return { isModalOpen, submit, state }
},
}
Check this repo for the complete repo: the files are UserCrud.vue & Create.vue
You should pass the user object as parameter then send it as body for the put request by setting the id as param :
<button #click="update(user)">Update</button>
...
async function update(user) {
let _user={...user,name:'Malik'};//example
await axios.put(`/users/${user._id}`,_user);
const { data } = await axios.get(`/users`)
state.users = data
}
You could use the same code of adding new user for the update by defining a property called editMode which has true in update mode and based on this property you could perform the right request
export default {
components: { Modal },
emits: ['new-user-added','user-edited'],
props:['editMode','user'],
setup(props, { emit }) {
const isModalOpen = ref(false)
const state = reactive({
form: {
name: '',
email: '',
avatar: '',
},
})
onMounted(()=>{
state.form=props.user;//user to edit
})
async function submit() {
if(props.editMode){
const { data } = await axios.put('/users/'+props.user._id, state.form)
emit('user-edited', data)
}else{
const { data } = await axios.post('/users', state.form)
emit('new-user-added', data)
state.form.email = ''
state.form.name = ''
state.form.avatar = ''
}
isModalOpen.value = false
}
return { isModalOpen, submit, state }
},
}
I'm using aws-sdk in my service to send emails. I'm getting below exception to a code which was working fine before.
const aws = require('aws-sdk');
var params = {
Destination: {
ToAddresses: [
'checkMail#gmail.com'
]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "HTML_FORMAT_BODY"
},
Text: {
Charset: "UTF-8",
Data: "this is sample"
}
},
Subject: {
Charset: 'UTF-8',
Data: 'Test email'
}
},
Source: 'AWS Services<awsEmails#awsService.com>'
ReplyToAddresses: [
'AwsServices<noreply#awsServices.com>'
],
};
// Create the promise and SES service object
var emailPromise = new aws.SES({apiVersion: '2010-12-01'}).sendEmail(params).promise();
// Handle promise's fulfilled/rejected states
emailPromise.then(
function(data) {
//my logic on success goes here
}).catch(
function(err) {
//my logic on error goes here
});
I have tried using different API calls for email from AWS but all returns the same error.
Avoid require ALL aws-sdk if it's just to use a single service. For using SES, you can yarn add #aws-sdk/client-ses and then use it const { SESClient, SendEmailCommand } = require("#aws-sdk/client-ses");
I show you here a full exemple of sending email with SES in a nodeJS lambda function:
const {
SESClient,
SendEmailCommand,
} = require("#aws-sdk/client-ses");
const REGION = "eu-west-3"; // Use you AWS region
const ses = new SESClient({ region: REGION });
exports.handler = async function (event) {
const path = event.path;
if (path === "/send-email") {
const peopleAmount = 12;
const params = {
Source: "John Wick <john.wick#killer.com>",
Destination: {
ToAddresses: ["adresse1#test.com"],
},
Message: {
Body: {
Html: {
Data: `<span>This email is about <b>${peopleAmount}</b> people.</span>`,
},
},
Subject: {
Data: "Email Title",
},
},
};
try {
const data = await ses.send(new SendEmailCommand(params));
return {
statusCode: 200,
body: peopleAmount,
};
} catch (e) {
console.error(e, e.stack);
return {
statusCode: 400,
body: "Sending failed",
};
}
}
}
I hope it helps, here is documentation to use SES email template.
I tried to integrate PayPal Express Checkout to my webapp (server-side REST) and I managed to:
get create-payment working
However, when I tried to login with a sandbox test buyer account, it failed to process the payment.
There's a 400 Bad request error for the POST request:
POST https://www.sandbox.paypal.com/webapps/hermes/api/batch/setbuyer 400 (Bad Request)
with the following response:
{
"ack": "success",
"data": {
"buyerEligibility": {
"ack": "success",
"data": {
"eligible": true,
"clearedRT": false
},
"meta": {
"calc": "8f7cc8e266c07",
"rlog": "PVs6nBwuIQ9X2gSdIEqzR%2BxkmohYC3WlOiW4HauQ%2FY%2Fh%2BkWFfmr2pOeyxVs3sSiqXDydWuJ%2B6QWLAsZZVtRfIA_15d276b99bf"
},
"server": "xG7Ol-1A5r4xEqHEubzBtkj6LgLo88Z7UFOPmqsoK957Q11gkENbvzjGa02RjhyhvYG_ff2SZRFgHYp0Nq5rCCIdwQAwbwL-RkZ0piofvsP6-i9NmpkouuuH47EBynDbMencyfNKhT-cIewGtGK2jKUX_q0FaWq9Gx0MaRB6QBwINBmRQB5tAuklfWE8ooIwOO7szgPXVg9pOXWI2ukxup08j93HODToZ4DnSLuqCK6XM2M49-_DDSyS6GviI3gWrBy7BLOsHky"
},
"eConsent": {
"ack": "success",
"data": {
"required": false
},
"meta": {
"calc": "8f7cc8e266c07",
"rlog": "PVs6nBwuIQ9X2gSdIEqzR%2BxkmohYC3WlOiW4HauQ%2FY%2Fh%2BkWFfmr2pOeyxVs3sSiqXDydWuJ%2B6QWLAsZZVtRfIA_15d276b99bf"
},
"server": "-bDk6FVAJFycsTL-R5q_CGdrJwDz9XbAF9KqMHpr6QIMACZ6IA5zQ_BVyqi3jy6w9pKC5SS4TBrpDB_OJC0rU1W5wz5XBgo3ze_iOG0gDEwxuzu7WtAT1Nv5_VmLhmUWIdMm7qtgfy1y11v18zXSxhATUDaRI8hNdlnArSlBtKVNGWkhCD4OTp4KvSBXQ3lLHm-wCSrJzhpEmBoNZmDQMrd4wv1YEYA0VFPG1cPHapq9t4xJMLfiZOad10irqxJP"
},
"createCheckoutSession": {
"ack": "contingency",
"contingency": "PAYER_CANNOT_PAY",
"errorData": {
"cause": "",
"step_up_context": {}
},
"meta": {
"calc": "8f7cc8e266c07",
"rlog": "PVs6nBwuIQ9X2gSdIEqzR%2BxkmohYC3WlOiW4HauQ%2FY%2Fh%2BkWFfmr2pOeyxVs3sSiqXDydWuJ%2B6QWLAsZZVtRfIA_15d276b99bf"
},
"server": "-eKOVjOLP5i0k_9Et8_N5HyfLSVBzycsA2AE8UY8RD88MnM3729QBQoHY2eD3sMhSThBqdYmvFoARIAbkHNoOT9jsHzAUCk1CtbA717xHK5gSuYujf5mvuDJQFXWlPEDBk7XFlZSyhUWy8VGKvYWwWhuTSzcjMdKIzRI_XTjfA2hQpzIvkbRQ5jLMDIIKeNm1XrF3mEMN3gkHzZIc2OBiRaVEA2Q0se_uVgEEGIbSgN2aeSOeh4WiMC08zUCvmdCLyCP0ZyE24fzDvL4ZMUurG"
}
},
"meta": {
"calc": "8f7cc8e266c07",
"rlog": "PVs6nBwuIQ9X2gSdIEqzR%2BxkmohYC3WlOiW4HauQ%2FY%2Fh%2BkWFfmr2pOeyxVs3sSiqXDydWuJ%2B6QWLAsZZVtRfIA_15d276b99bf"
},
"server": "JwJRYq2SF3kUujC16-VsiMQu8IDN_RxPNOz8wY8m8YD4P3PzhHZB73hNd_IM9PktfJcPPHx2RyVUk1PV8bC2lLtejwTFKzq-7QDM9nLmxJLw7os2tgLnGYAebFJAkmIt2fFvlncVMrAg9bAsMF9INhPqixaCEWn7ug9OcPCci_3autJi3cvmTLb_8XvTaGBpPxI0ASQnkXTSVJa2GPIptYhGVHFN5N92hFdxzwp2uYQhHeJrePmExV4NlLd0s_wa"
}
My client side implementation for PayPal Express Checkout:
class PayPalButton extends Component {
render() {
const Btn = paypal.Button.driver('react', {React, ReactDOM});
const CREATE_PAYMENT_URL = `${ROOT_URL}/paypal/create-payment/${this.props.regId}`;
const EXECUTE_PAYMENT_URL = `${ROOT_URL}/paypal/execute-payment/${this.props.regId}`;
const token = localStorage.getItem('deotoken');
let client = {
sandbox: 'TO_BE_REPLACED_WITH_SANDBOX_CLIENT_ID'
};
let payment = () => {
return paypal.request({
method: 'post',
url: CREATE_PAYMENT_URL,
headers: {
authorization: token
}
})
.then(function(data) {
return data.id;
});
};
let onAuthorize = (data) => {
return paypal.request({
method: 'post',
url: EXECUTE_PAYMENT_URL,
headers: {
authorization: token
},
json: {
paymentID: data.paymentID,
payerID: data.payerID
}
}).then(function() {
// The payment is complete!
// You can now show a confirmation message to the customer
console.log('done');
});
};
return (
<div>
<Btn env={'sandbox'}
client={client}
payment={payment}
commit={true}
onAuthorize={onAuthorize}
/>
</div>
);
}
My server side implementation):
module.exports = {
createPayment(req, res, next) {
const { registration_id } = req.params;
const { user } = req;
Registration.findById(registration_id)
.populate({ path: 'category', model: 'category' })
.populate({ path: 'orders.meal', model: 'meal' })
.then(reg => {
if (reg) {
const categoryItem = [{
name: reg.category.name,
sku: reg.category.name,
price: reg.category.price,
currency: 'MYR',
quantity: 1
}];
const ordersItems = reg.orders.map(order => {
return {
name: order.meal.name,
sku: order.meal.name,
price: order.meal.price,
currency: 'MYR',
quantity: order.quantity
}
});
const create_payment_json = {
intent: 'sale',
payer: {
payment_method: 'paypal'
},
redirect_urls: {
return_url: 'http://localhost:8080/',
cancel_url: 'http://localhost:8080/'
},
transactions: [{
item_list: {
items: [...categoryItem, ...ordersItems]
},
amount: {
currency: 'MYR',
total: reg.totalBill
}
}]
};
paypal.payment.create(create_payment_json, function(err, payment) {
if (err) {
next(err);
} else {
res.send(payment);
}
})
} else {
return res.status(422).send({error: 'Registration not found'});
}
})
.catch(next);
},
executePayment(req, res, next) {
const { registration_id } = req.params;
const { paymentID, payerID } = req.body;
const execute_payment_json = {
payer_id: payerID
}
paypal.payment.execute(paymentID, execute_payment_json, function(err, paypalResponse) {
if (err) {
next(err);
} else {
if (paypalResponse.state === 'approved') {
const payment = new Payment({
user: req.user._id,
registration: registration_id,
amount: paypalResponse.transactions[0].amount.total,
currency: paypalResponse.transactions[0].amount.currency,
paypalPaymentId: paypalResponse.id
});
payment.save()
.then(p => res.send(p))
.catch(next);
} else {
res.status(422).send({ error: 'Payment not approved' });
}
}
});
}
};
What is the issue? How can I make this work?
I have faced same issue.
I have set INR as my currency in my paypal sandbox, but sending amount as USD from API call.
So, I think we have to make transaction in currency that we set in sandbox.
Previous Payload:
transactions: [{
item_list: {
items: [...categoryItem, ...ordersItems]
},
amount: {
currency: 'USD',
total: reg.totalBill
}
}]
After Change Payload:
transactions: [{
item_list: {
items: [...categoryItem, ...ordersItems]
},
amount: {
currency: 'INR',
total: reg.totalBill
}
}]
After changing currency, my code works fine !!