Hi I'm creating a Rider app I want to push a Notification and show alert dialog to Rider when a Delivery Request is placed for him in Rest API, Delivery Request is coming from Rest API but I'm unable to show Notification to Rider . If any one have done this before or have any Idea please Guide.
Thanks in Advance.
use the following code:
http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'to': deviceToken,
},
),
);
you can find server token in your firebase console->Project settings->Cloud messaging tab->server key
and device token is found after installing firebase_messaging: package and
FirebaseMessaging fcm=FirebaseMessaging();
print(fcm.getToken());//deviceToken
Related
I want to intigrate stripe payment but i got this error
** FlowController must be successfully initialized using configureWithPaymentIntent() or configureWithSetupIntent() before calling presentPaymentOptions()**
How solve this error also it is not displaying any card
Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "email,amount: 50.0);
},
child: Text("Pay20\$"),
),
),
Future<void> intpayment(
{required String email, required double amount})async{
try{
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
final jsonresponse=jsonDecode(response.body); Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonresponse['paymentIntent'],
merchantDisplayName: 'Zohaib',
));
await Stripe.instance.presentPaymentSheet();
Fluttertoast.showToast(
msg: "payment successfully",
);
}
catch(e){
if (e is StripeException) {
Fluttertoast.showToast(
msg: "Stripe error $e",
);
}
Fluttertoast.showToast(
msg: "$e",
toastLength: Toast.LENGTH_SHORT, );
}
}
You need to create the PaymentIntent on the server-side and not within your flutter app.
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
Instead of calling the Stripe API directly as you did in the code above, you should call your own API and generate a Payment Intent and just send the client_secret to your flutter App, otherwise you would be exposing your secret key and thus giving access to your data. This is described here.
Once you do this server-side part the rest is explained here.
I have implemented chat message app in which user can
reply to chat from push
notification when app is killed/background/foreground.
But when app is in Terminated state API call not work in
firebaseMessagingBackgroundHandler.
Its stuck on sendNotification function.
Code to handle background events:
Future<void>
firebaseMessagingBackgroundHandler(RemoteMessage message)
async {
await GetStorage.init();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
//Call HTTP request <Stuck here
sendNotification(
personUid,
title,
body,
notificationTypeId,
chatRoomId,
userTokenDummy,
userToken,
serverKey,
currentUserId,
currentUserToken,
);
}
Here is a code for API request:
sendNotification({
required String personUid,
required String title,
required String body,
required int notificationTypeId,
String? chatRoomId,
String? userTokenDummy,
String? userToken,
String? serverKey,
String? currentUserId,
String? currentUserToken,
}) async {
try {
final response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
HttpHeaders.contentTypeHeader:
'application/json',
HttpHeaders.authorizationHeader: 'key=$serverKey'
},
body: jsonEncode(
<String, dynamic>{
"data": <String, dynamic>{
"title": title,
"body": body,
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"senderId": currentUserId,
"senderToken": currentUserToken,
"notificationTypeId": notificationTypeId,
"chatRoomId": chatRoomId,
},
"android": {
"priority": "high",
},
"apns": {
"headers": {"apns-priority": "10"}
},
"to": userToken,
"content_available": true,
"mutable-content": 1,
"priority": "high",
},
),
);
return response;
} catch (e) {
console(e.toString());
}
}
Yes,you can call Http request inside firebaseMessagingBackgroundHandler. But make sure that this api is not taking too much time. Because long and intensive tasks impacts on device performance. Also make sure that there is not exception or error in the api which causes the device to freeze.
To make sure that api is not running forever place a timeout in http class.
for more refer to firebase documentation : https://firebase.google.com/docs/cloud-messaging/flutter/receive
How to disable sound when FCM is send, I want to send FCM without sound..
I'm able right now to send succesfuly FCM with sound
var body = jsonEncode(<String, dynamic>{
'notification': <String, dynamic>{
"body": userModel.userName +' '+ 'Followed you',
// 'title': "${userModel.userName}"
'title':'',
'sound':""
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
"type": NotificationType.Follow.toString(),
"senderId": userModel.userId,
"title": "title",
"body": userModel.userName +' '+ 'Followed you',
"postId": ""
},
'to': userModel.userName
});
body: body);
print(response.body.toString());
}
I can send an FCM message to my Flutter app when the app has subscribed to "test_fcm_topic" as a topic. But if I subscribe to anything else IE: "redrobin" I don't receive the notification. I've tried sending from both the Flutter app and from Postman. In both cases the terminal shows the instance is received but there is no sound or notification popup.
I'm completely baffled as to why I cannot change the topic to anything other than "test_fcm_topic". Why would it work with one topic but not in the other? How can I even begin to troubleshoot?
Here's the code I use to subscribe;
FCMConfig.init(onBackgroundMessage: firebaseMessagingBackgroundHandler).then((value) {FCMConfig.subscribeToTopic("test_fcm_topic");});
Here's the send code in Flutter;
void send() async {
await http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a body',
'title': 'Banana'
},
'priority': 'high',
'data': <String, dynamic>{
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
},
'to': '/topics/test_fcm_topic',
},
),
);
}
For Postman I use these key pairs in the headers
Key: Authorization Value: key= server key
Key: Content-Type: Value: application/json
And this is the Raw JSON Body;
{
"to" : "/topics/test_fcm_topic",
"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification",
"title": "Banana"
},
"data" : {
"body" : "This is a body",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
Using your code like this works like a charm when testing on my device:
void send(String serverToken) async {
Response response = await post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':'key=$serverToken'
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{'body': 'This is a body', 'title': 'Banana'},
'priority': 'high',
'data': <String, dynamic>{'audioid': '139', 'title': 'done all over time', 'name': 'Greengirl'},
'to': '/topics/hi',
},
),
);
print(response.body);
}
But please note, that you must subscribe to the topic 'hi3' used in this example.
By running :
FirebaseMessaging.instance.subscribeToTopic('hi3'); on the client you want to receive these broadcasts.
Output of the function above is:
I/flutter (18090): {"message_id":1225534686323630021}
followed by:
D/FLTFireMsgReceiver(18090): broadcast received for message
They even run faster than firebase console push notifications.
I currently using FCM to push notification to my flutter app.
I try to launch the app when the user tap on a notification when the app is in background
I got this terminal log when I try to tap on a notification
E/FirebaseMessaging(24830): Notification pending intent canceled
I also put this in my AndroidManifest.xml as the official document
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
This is my payload of the push notification
{ notification:
{
title: 'title',
body: 'body',
badge: '1',
icon: 'https://miro.medium.com/max/11400/1*lS9ZqdEGZrRiTcL1JUgt9w.jpeg',
click_action: 'FlUTTER_NOTIFICATION_CLICK',
sound: 'default'
},
data: { type: '4' }
}
What did I miss?
first of all your payload should be encoded as JSON :
{
'notification': {
'body': 'this is a body',
'title': 'this is a title'
},
'priority': 'high',
'data': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done'
},
'to': await firebaseMessaging.getToken(),
}
after this try remove 'click_action': 'FLUTTER_NOTIFICATION_CLICK', from your payload and check its work or not