non-local notification using workManager flutter - flutter

i tried to send notification to another device when the app is terminated using workManager
it does not work, however the same function works if i use it without workManager
here is the code
in the main
await Workmanager().initialize(callBAckDispatcher, isInDebugMode: true);
callBackDispathcer
callBAckDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
Workmanager().executeTask((taskName, inputData) async {
if (taskName == "t") {
int id = 7
await sFunction(id, await returnUserName());
}
return Future.value(true);
});
}
sFunction
sFunction(int id, String sender) async {
List<Map> response =
await SQLdb().readData('''SELECT * FROM `timer_chat` WHERE id = $id
''');
String reciever = response[0]['reciever'];
String message = response[0]['message'];
try {
String currentToken = await auth.getusertoken(reciever);
auth.sendnotify("my app",
"your message has been sent: " + message, "1", currentToken);
} catch (e) {
print("notification did not send: " + e.toString());
}
}
finally sendnotify
sendnotify(String title, String body, String id, String token) async {
try {
await http.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': body.toString(),
'title': title.toString()
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': "FLUTTER_NOTIFICATION_CLICK",
'id': id.toString(),
"name": "me",
"lastname": "wolf"
},
"to": token
},
),
);
} catch (e) {
print("something went wrong in notiiiii" + e.toString());
}
}
i'm sending notifications using firebase cloud messaging API. it worked fine inside the app but in workManager it does not. any idea why?
thank you

Related

How to send a user to a specific page via firebase notification when the app is terminated in flutter?

Main Screen
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewScreen(info: payload.toString())));
} else {}
} catch (e) {}
return;
});
void sendPushMessage(String token, String body, String title) async {
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key=thekey'
},
body: jsonEncode(<String, dynamic>{
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'status': 'done',
'body': body,
'title': title
},
"notification": <String, dynamic>{
"title": title,
"body": body,
"android_channel_id": "androidchannelid"
},
"to": token,
}),
);
} catch (e) {
if (kDebugMode) {
print('error push notifications');
}
}
}
When the notification is received it should be send to the new screen and not the main screen.
This code works when the app is in background or foreground but it is not working when the app is terminated.
What should i do?
Use to getInitialMessage to check if there is a message when a application is opened.
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
// TODO navigate to a specific page
}
See Handling Interaction for details.

i want to send notification when receive a meesage in my chat app but it didn't work

i tried method using firebase_messaging: 7.0.1 but now its firebase_messaging: 14.0.2.
i got this error :
Converting object to an encodable object failed: Instance of 'Future<String?>'
sendNotif(String? title, String? body, String? id) async {
try {
await http
.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': body.toString(),
'title': title.toString()
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': id.toString(),
},
'to': FirebaseMessaging.instance.getToken(),
},
),
)
.then((value) => (value) {
print("send succeffuly");
});
} catch (e) {
print("THe ERROR : $e");
}
}
As the error message says, FirebaseMessaging.instance.getToken() returns a Future<String>, while the post API expects only current (non-Future) values.
The simplest fix is to await the value:
'to': await FirebaseMessaging.instance.getToken(),

How can we send push notification to an specific user while app is exited. - FLUTTER

I am actually working with a e-commerce app and want to send notification to a delivery boy when order is placed from user app.
How can we identify the specific delivery boy app from backgroud (when app is exited).
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage
message) async {
await Firebase.initializeApp();
SharedPreferences _prefs = await SharedPreferences.getInstance();
print('A message just showed : ${message.messageId}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// <------------Local Notification Initilization-------------->
FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
runApp(MyApp());
}
Use http request to send notifications, and use topic parameter for specific user selection, check the code example that I've used in my case:
final String serverToken = 'YOUR_SERVER_TOKEN_HERE';
FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
Future<Map<String, dynamic>> sendAndRetrieveMessage(String typeOfNotification,
{String? sellerId, String? chatId, String? postId}) async {
NotificationSettings settings = await firebaseMessaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
String notification = getNotificationMessage(typeOfNotification);
notificationMsg.value = notification;
addToNotifications(sellerId!, notification, postId ?? "$userId", chatId ?? "$userId");
print('User granted permission: ${settings.authorizationStatus}');
String topic = '';
if (typeOfNotification == 'live') {
topic = "/topics/$userId";
} else if (typeOfNotification == 'post') {
topic = "/topics/$userId";
} else {
topic = "/topics/${sellerId}_personal";
}
await http.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': "${userIsASeller.value ? shopName.value : userName.value} $notification",
'title': "Shopenlive",
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
'title': "Shopenlive",
'body': "${userIsASeller.value ? shopName.value : userName.value} $notification",
},
'to': topic,
},
),
);
final Completer<Map<String, dynamic>> completer = Completer<Map<String, dynamic>>();
/* firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
completer.complete(message);
},
); */
return completer.future;
}

How to create customer in stripe payment gateway flutter?

I am using stripe sdk for payment and trying to create customer in that ,
static Future<Map<String, dynamic>> createcustomer() async {
try {
var body = {
'name': 'Jenny Rosen',
'address': {
'line1': '510 Townsend St',
'postal_code': '98140',
'city': 'San Francisco',
'state': 'CA',
'country': 'US',
}
};
var response = await http.post(
'https://api.stripe.com/v1/customers',
body: json.encode(body),
headers: StripeService.headers
);
print('resvfdg: ${jsonDecode(response.body)}');
return jsonDecode(response.body);
} catch (err) {
print('err charging user: ${err.toString()}');
}
return null;
}
i am getting the error code: parameter_unknown,message: Received unknown parameter ,
how to create customer in stripe ?? or what i am missing in this ?
i don't know how to apply this and i need to create customer for doing international payment outside india , if i done payment in "INR" it will working properly , but for any other currency they asked for name and address.
I'm using Dio, this code is working for me:
static Future<Map<String, dynamic>> createcustomer() async {
try {
var data = {
'name': 'Jenny Rosen',
'address': {
'line1': '510 Townsend St',
'postal_code': '98140',
'city': 'San Francisco',
'state': 'CA',
'country': 'US',
}
};
Response response = await Dio().post('https://api.stripe.com/v1/customers',
data: data,
options: Options(contentType:Headers.formUrlEncodedContentType,
headers: {
'Authorization': 'Bearer ${secret}', // your secret key
}
),
);
print('response: ${jsonDecode(response.data)}');
return jsonDecode(response.data);
} catch (err) {
print('err charging user: ${err.toString()}');
}
return null;
}
I have used this api is working fine but response is paramter unknown
{error: {code: parameter_unknown, doc_url: https://stripe.com/docs/error-codes/parameter-unknown, message: Received unknown parameter: {"address":"sss","email":"aryan#gmail.com","name":"aryan","phone":"953667"}, param: {"address":"sss","email":"aryan#gmail.com","name":"aryan","phone":"953667"}, type: invalid_request_error}}
Flutter Code
Future createcustomer() async {
try {
var body = {
"address": "sss",
"email": "aryan#gmail.com",
"name": "aryan",
"phone": "95366710",
};
//final response = await http.post(Uri.parse("https://api.stripe.com/v1/customers"),
final response = await http.post(Uri.parse("https://api.stripe.com/v1/customers"),
headers: {
"Content-Type": "application/x-www-form-urlencoded","Authorization": "Bearer ${sKey}",
},
body: json.encode(body),
);
print('resvfdg: ${jsonDecode(response.body)}');
return jsonDecode(response.body);
} catch (err) {
print('err charging user: ${err.toString()}');
}
}

How to use Razorpay Orders API in Flutter?

I'm implementing a payment gateway in my flutter application. So Razorpay recommends me to use Orders API. But I don't get any ways to implement Orders API.
I had referred the below documentation. It contains examples for java, PHP, etc. But nothing found for Flutter / Dart.
https://razorpay.com/docs/payment-gateway/orders/integration/#example
Thanks in advance.
Future<void> generate_ODID() async {
var orderOptions = {
'amount': 50000, // amount in the smallest currency unit
'currency': "INR",
'receipt': "order_rcptid_11"
};
final client = HttpClient();
final request =
await client.postUrl(Uri.parse('https://api.razorpay.com/v1/orders'));
request.headers.set(
HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
String basicAuth = 'Basic ' +
base64Encode(utf8.encode(
'${'YourKEY'}:${'YourSECRET'}'));
request.headers.set(HttpHeaders.authorizationHeader, basicAuth);
request.add(utf8.encode(json.encode(orderOptions)));
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print('ORDERID'+contents);
String orderId = contents.split(',')[0].split(":")[1];
orderId = orderId.substring(1, orderId.length - 1);
Fluttertoast.showToast(
msg: "ORDERID: " +orderId,
toastLength: Toast.LENGTH_SHORT);
Map<String, dynamic> checkoutOptions = {
'key': 'YourKEY',
'amount': 11100,
'name': 'Demo',
'description': 'Fssai Registrtion Charge',
'prefill': {'contact': '8910407549', 'email': 'xx.xx#gmail.com'},
'external': {
'wallets': ['paytm']
}
};
try {
_razorpay.open(checkoutOptions);
} catch (e) {
print(e.toString());
}
});
}
I am using this same code snippet but when I am trying to do payments with google pay then it will fail with "Your money is not debited, Your server is busy" Error, but when I try to do with providing UPI Id manually then the transaction goes smoothly, otherwise transactions not done using UPI. Is there any way to solve this?
final client = HttpClient();
final request =
await client.postUrl(Uri.parse('https://api.razorpay.com/v1/orders'));
request.headers.set(
HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
String basicAuth = 'Basic ' +
base64Encode(utf8.encode(
'${dotenv.env['RAZORPAY_KEY']!}:${dotenv.env['RAZORPAY_SECRET']!}'));
request.headers.set(HttpHeaders.authorizationHeader, basicAuth);
request.add(utf8.encode(json.encode(orderOptions)));
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
String orderId = contents.split(',')[0].split(":")[1];
orderId = orderId.substring(1, orderId.length - 1);
Map<String, dynamic> checkoutOptions = {
'key': dotenv.env['RAZORPAY_KEY']!,
'amount': total * 100,
"currency": "INR",
'name': 'E Drives',
'description': 'E Bike',
'order_id': orderId, // Generate order_id using Orders API
'timeout': 300,
};
try {
_razorpay.open(checkoutOptions);
} catch (e) {
log.e(e.toString());
}
You can use HttpClient and send a request to the Razorpay Orders API.
Hope this answers your question.
Thankfully, Razorpay has Flutter package which you can use. The following code snippet might help :
import 'package:razorpay_flutter/razorpay_flutter.dart';
_razorpay = Razorpay();
var options = {
'key': '<YOUR_KEY_ID>',
'amount': 100, //in the smallest currency sub-unit.
'name': 'Acme Corp.',
'order_id': 'order_EMBFqjDHEEn80l', // Generate order_id using Orders API
'description': 'Fine T-Shirt',
'prefill': {
'contact': '9123456789',
'email': 'gaurav.kumar#example.com'
}
};
_razorpay.open(options);
Please go through this page for further details. And this YouTube video will help as well.
You can use the Below code. it's working as expected.
createOrderId(amount, description, id, userId) async {
final int Amount = int.parse(amount) * 100;
http.Response response = await http.post(
Uri.parse(
"https://api.razorpay.com/v1/orders",
),
headers: {
"Content-Type": "application/json",
"Authorization":
"Basic ${base64Encode(utf8.encode('testKey:secreateKey'))} "
},
body: json.encode({
"amount": Amount,
"currency": "INR",
"receipt": "OrderId_$id",
"notes": {"userId": "$userId", "packageId": "$id"},
}));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
openCheckout(amount, description, id, userId, data["id"]);
}
print(response.body);
}
void openCheckout(amount, description, id, userId, String orderId) async {
final int Amount = int.parse(amount) * 100;
var options = {
'key': 'testkey',
'amount': Amount,
'name': 'Name',
'description': description,
'order_id': orderId,
// "prefill": {
// "name": name,
// "email": emails,
// },
"notes": {"userId": "$userId", "packageId": "$id"},
'external': {
'wallets': ['paytm']
}
};
try {
_razorpay.open(options);
} catch (e) {
debugPrint('Error: e');
}
}
Might be helpful for someone.
Hope you set up all the necessary things.
Step 1: creating Order using Razorpay official Order Api:
//* create order##############################################################
void createOrder() async {
String username = 'xxxxxxxxxx';// razorpay pay key
String password = "xxxxxxxxxxxxxxxx";// razoepay secret key
String basicAuth =
'Basic ${base64Encode(utf8.encode('$username:$password'))}';
Map<String, dynamic> body = {
"amount": 1 * 100,
"currency": "INR",
"receipt": "rcptid_11"
};
var res = await http.post(
Uri.https(
"api.razorpay.com", "v1/orders"), //https://api.razorpay.com/v1/orders // Api provided by Razorpay Official 💙
headers: <String, String>{
"Content-Type": "application/json",
'authorization': basicAuth,
},
body: jsonEncode(body),
);
if (res.statusCode == 200) {
openCheckout(jsonDecode(res.body)['id']); // 😎🔥
}
print(res.body);
}
//*#################################################################
Step 2: Open Razorpay checkout interface.
After getting orderId from Razorpay official Api, pass the id when calling openCheckout(jsonDecode(res.body)['id']); function
void openCheckout(String orderId) async {
var options = {
'key': 'xxxxxxxxxxxxxxxx',
"amount": 1 * 100,
'order_id': orderId,
'name': 'main.co.in',
// 'prefill': {'contact': '', 'email': 'test#razorpay.com'},
'external': {
'wallets': ['paytm']
}
};
try {
razorpay.open(options);
} catch (e) {
debugPrint('Error: e');
}
}
3rd Step: Signature verification.
This is important if you automatically wanna transfer your amount to your bank account.
for Hmac SHA key , install this package: crypto:
handlerPaymentSuccess(PaymentSuccessResponse response) {
final key = utf8.encode('NgDLPyiDRPuQpcXy1E3GKTDv');
final bytes = utf8.encode('${response.orderId}|${response.paymentId}');
final hmacSha256 = Hmac(sha256, key);
final generatedSignature = hmacSha256.convert(bytes);
if (generatedSignature.toString() == response.signature) {
log("Payment was successful!");
//Handle what to do after a successful payment.
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Success : payment successful"),
// content: const Text("Are you sure you wish to delete this item?"),
actions: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(true);
// PlaceOrderPrepaid();
},
child: Text("OK"))
// ),
],
);
},
);
} else {
log("The payment was unauthentic!");
}
}
Thats it!