Flutter open whatsapp with text message - flutter

I want to open whatsapp from my Flutter application and send a specific text string. I'll select who I send it to when I'm in whatsapp.
After making some research I came up with this:
_launchWhatsapp() async {
const url = "https://wa.me/?text=Hey buddy, try this super cool new app!";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Which works ok ish, however there are two problems:
As soon as I make the text string into multi words it fails. So if I change it to:
_launchWhatsapp() async {
const url = "https://wa.me/?text=Hey buddy, try this super cool new app!";
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Then the Could not launch $url is thrown.
I have whatsapp already installed on my phone, but it doesn't go directly to the app, instead it gives me a webpage first and the option to open the app.
Here is the webpage that I see:
Any help on resolving either of these issues would be greatly appreciated.
Thanks
Carson
P.s. I'm using the Url_launcher package to do this.

From the official Whatsapp FAQ, you can see that using "Universal links are the preferred method of linking to a WhatsApp account".
So in your code, the url string should be:
const url = "https://wa.me/?text=YourTextHere";
If the user has Whatsapp installed in his phone, this link will open it directly. That should solve the problem of opening a webpage first.
For the problem of not being able to send multi-word messages, that's because you need to encode your message as a URL. Thats stated in the documentation aswell:
URL-encodedtext is the URL-encoded pre-filled message.
So, in order to url-encode your message in Dart, you can do it as follows:
const url = "https://wa.me/?text=Your Message here";
var encoded = Uri.encodeFull(url);
As seen in the Dart Language tour.
Please note that in your example-code you have put an extra set of single quotes around the text-message, which you shouldn't.
Edit:
Another option also presented in the Whatsapp FAQ is to directly use the Whatsapp Scheme. If you want to try that, you can use the following url:
const url = "whatsapp://send?text=Hello World!"
Please also note that if you are testing in iOS9 or greater, the Apple Documentation states:
Important
If your app is linked on or after iOS 9.0, you must declare the URL schemes you pass to this method by adding the LSApplicationQueriesSchemes key to your app's Info.plist file. This method always returns false for undeclared schemes, whether or not an appropriate app is installed. To learn more about the key, see LSApplicationQueriesSchemes.
So you need to add the following keys to your info.plist, in case you are using the custom whatsapp scheme:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>

till date: 27-06-2022
using package: https://pub.dev/packages/url_launcher
dependencies - url_launcher: ^6.1.2
TextButton(
onPressed: () {
_launchWhatsapp();
},
)
_launchWhatsapp() async {
var whatsapp = "+91XXXXXXXXXX";
var whatsappAndroid =Uri.parse("whatsapp://send?phone=$whatsapp&text=hello");
if (await canLaunchUrl(whatsappAndroid)) {
await launchUrl(whatsappAndroid);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("WhatsApp is not installed on the device"),
),
);
}
}

Here is new update way...
whatsapp() async{
var contact = "+880123232333";
var androidUrl = "whatsapp://send?phone=$contact&text=Hi, I need some help";
var iosUrl = "https://wa.me/$contact?text=${Uri.parse('Hi, I need some help')}";
try{
if(Platform.isIOS){
await launchUrl(Uri.parse(iosUrl));
}
else{
await launchUrl(Uri.parse(androidUrl));
}
} on Exception{
EasyLoading.showError('WhatsApp is not installed.');
}
}
and call whatsapp function in onpress or ontap function

For using the wa.me domain, make sure to use this format...
https://wa.me/123?text=Your Message here
This will send to the phone number 123. Otherwise, you will get an error message (see? https://wa.me/?text=YourMessageHere ). Or, if you don't want to include the phone number, try this...
https://api.whatsapp.com/send?text=Hello there!
Remember, wa.me requires a phone number, whereas api.whatsapp.com does not. Hope this helps!

I know it is too late for answering this, but for those who want the same functionality, the current way is to do it like this:
launchUrl(Uri.parse('https://wa.me/$countryCode$contactNo?text=Hi'),
mode: LaunchMode.externalApplication);

if you will use URL Launcher then the whatsapp link will be open on web browser. So you need to set parameter - not to open on safari browser. The complete code you can find on this flutter tutorial.
But for your case use below code.
await launch(whatappURL, forceSafariVC: false);

Today i am adding solution its working fine on my desktop and phone
Add 91 if your country code is +91
Remember not add any http or https prefix otherwise wont work.
whatsapp://send?phone=9112345678&text=Hello%20World!

Related

What would be better way to open external URL with Affiliate Links?

I want to offer some products/services on my Flutter app through affiliate links (https://www.amazon.com/REF######).
What would be a better way to lunch this URL and improve the chances of getting the refer from the link? I've some options below, but let me know if I could make some improvments on my code.
void launchAmazon() async {
const url = 'https://www.amazon.com/REF######';
if (await canLaunch(Uri.encodeFull(url))) {
await launch(url);
} else {
throw ‘Could not launch $url’;
}
Second option:
onPressed: () async {
if (await launchUrlString("${Get.arguments[4]}",
mode: LaunchMode.externalApplication)) {
await launchUrlString("${Get.arguments[4]}",
mode: LaunchMode.externalApplication);
} else {
throw 'Não foi possível carregar o endereço: "${Get.arguments[4]}"url';
}
},
Do I need to add?
forceWebView: true, enableJavaScript: true
Besides the URL launch question, do I need to do some extra configurations on my App?
Let me know if you need something else! Thanks!!
I've tried the second option already.
I do something similar to your option 1 and it's working fine. Just take note that opening links in an external app can cause your iOS apps to be rejected.
Apple desires apps to open all links in the application.

Flutter Dynamic linking not available for web apps?

My Use Case:
Users in my app can create lists of items. I want the users to be able to share a link to one of their lists.
I want individuals who click the shared link to see the list of items in a web browser and not need the app installed.
Create the Dynamic Link
The first thing I need to do is create a dynamic link for a user to share. I struggled with this at first and then looked at this question here: Flutter - How to pass custom arguments in firebase dynamic links for app invite feature?
After looking at that I build my own class like so:
class PackDynamicLinkService {
Future<Uri> createDynamicLink({required String packID}) async {
final DynamicLinkParameters parameters = DynamicLinkParameters(
// This should match firebase but without the username query param
uriPrefix: 'ttps://appName.app/p',
// This can be whatever you want for the uri, https://yourapp.com/groupinvite?username=$userName
link: Uri.parse('https://appName.app/p?pack=$packID'),
androidParameters: const AndroidParameters(
packageName: 'com.test.demo',
minimumVersion: 1,
),
iosParameters: const IOSParameters(
bundleId: 'com.test.demo',
minimumVersion: '1',
appStoreId: '',
),
);
final dynamicLink = await FirebaseDynamicLinks.instance.buildShortLink(
parameters,
shortLinkType: ShortDynamicLinkType.unguessable,
);
return dynamicLink.shortUrl;
}
}
I then called that function in my app and I am able to get a URL that looks like this: https://appName.app/p?pack=lVeSBUHoLX52zPqAiB9A
So far so good. Now I just need to click the link and read the parameter $packID that I passed to it inside my web app. Then I can route them to the correct view and display the list.
Processing Dynamic Link
in my marin.dart I tried to retrieve the params with:
//get link stuff
final PendingDynamicLinkData? initialLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
final Uri fullLink = initialLink.link;
print(fullLink.queryParameters['pack']);
}
but when I upload to firebase hosting to see if this code works for testing, I get this error:
Uncaught MissingPluginException(No implementation found for method
FirebaseDynamicLinks#getInitialLink on channel
plugins.flutter.io/firebase_dynamic_links)
After doing some more research it seems that firebase_dynamic_links package may not be available for web? So does that mean my original use case is not possible with flutter at this time?
You would want to take the link received and parse it using something like:
var PendingDynamicLinkData? initialLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (kIsWeb) {
String link = Uri.base;
initialLink = await
FirebaseDynamicLinks.instance.getDynamicLink(Uri.parse(link));
}
if (initialLink != null) {
final Uri fullLink = initialLink.link;
print(fullLink.queryParameters['pack']);
}
Here, we are checking if its a web app and then we can parse the dynamic link and get the info for it. We just check for the Uri that was used in our web app.

How to open subscriptions page in Play Store in Flutter

I want to edit my active subscription and for this I need to go to the play store.
Forcing the user to open the play store first, and then go to the settings page, and then open subscriptions is not suitable. Can this be done somehow in 1 click (not in browser)?
Options with opening in the browser are not suitable. I need to open the page with all subscriptions (https://play.google.com/store/account/subscriptions)
I need a redirect link market://...
Thank you!
I tried next packages: url_launcher, store_redirect etc.
Methods like: `
final Uri url =
Uri.parse('https://apps.apple.com/app/MyAppName/idXXXXX');
try {
if (await canLaunch(url.toString())) {
await launch(url.toString());
} else {
throw 'Could not launch $url';
}
} catch (e) {
print(e);
}
and
launchUrl(Uri.parse('https://play.google.com/store/account/subscriptions?sku=pro.monthly.testsku&package=com.example.app'));
I had to use only this method:
final url = Uri.parse('http://play.google.com/store/account/subscriptions');

How to send what'sapp message to any number from flutter?

I am using an api to get users data and i want to send messages to every users what's app number on click in flutter app. How to do this ?
https://www.youtube.com/watch?v=-wW2ZoDuFO4&t=391s
if windwos platform u can see my video
Use the plugin.
https://pub.dev/packages/url_launcher
final url = "https://wa.me/91XXXXXXXXXX?text=Hello";
//do not forgot to enter your country code instead of 91 and instead of XXXXXXXXXX enter phone number.
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url));
} else {
showSnackBar(message: "Can't share link", title: "Error");
}
if (!await launchUrl(Uri.parse(url))) throw 'Could not launch $url';

Flutter-web:url_launcher_web not launching email in browser

I've added a feature of sending feedback through email for my flutter web app. This is my code :
static void launchEmail(String subjectLine) async {
const emailId = Constants.ARUDITO_EMAIL;
print('opening email app for uploading content');
String url = "mailto:$emailId?subject=$subjectLine";
if (kIsWeb) {
if (await webLauncher.UrlLauncherPlugin().canLaunch(url)) {
await webLauncher.UrlLauncherPlugin().launch(
url,
useWebView: true,
enableDomStorage: true,
enableJavaScript: true,
useSafariVC: true,
webOnlyWindowName: 'Arudito',
headers: null,
universalLinksOnly: false,
);
} else {
throw 'Could not open an email app';
}
} else {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not open an email app';
}
}
}
pubspec.yaml includes :
dependencies:
flutter:
sdk: flutter
url_launcher: ^5.4.2
url_launcher_web: ^0.1.3+1
This code is not launching email in a web browser. It only opens a new tab. However, it is launching on selecting mail app in Windows. Can someone please tell what is the issue here?
I had exactly the same problem. I found a useful answer in another StackOverflow post.
There it is mentioned that if you just omit the canLaunch check and instead wrap the launch in a try-catch block it works on Flutter Web. I just tried, and it works nicely.
Btw, there is also a quite new Link widget in the url_launcher package, which makes it possible to create proper web links (including right-click support).
I had the exact issue. Click on any email link will just opens a new blank tab. That's it.
Took me hours to figure out.
Open Mail app on mac, settings, general, and there's an option for default email reader. It was selecting chrome. Change it to a real email client and it works as expected now.