如何打开 WhatsApp 聊天,其中包含来自我网站的多行预填充消息?

How to open a WhatsApp chat with a pre-filled message that spans on multiple lines from my website?

来自WhatsApp's FAQ section

WhatsApp provides a custom URL scheme to interact with WhatsApp:

If you have a website and want to open a WhatsApp chat with a pre-filled message, you can use our custom URL scheme to do so. Opening whatsapp://send?text= followed by the text to send, will open WhatsApp, allow the user to choose a contact, and pre-fill the input field with the specified text.

Here is an example of how to write this on your website:

<a href="whatsapp://send?text=Hello%20World!">Hello, world!</a>

如果我想让提到的 pre-filled message 像这样跨越多行怎么办:

Text on the first line
Text on the second line

Text on the third line
Text on the fourth line

我试过像这样将文本放在 <a href=""></a> 标签中:

<a href="whatsapp://send?text=First line\r\nSecond line\r\n\r\nThird line\r\nFourth line">Share on WhatsApp</a>

但它不起作用,消息在 WhatsApp 中显示如下:

First lineSecond lineThird lineFourth line

<a href=""></a>标签的URL中使用的PHP换行符\r\n需要编码。 urlencode() PHP 函数可用于执行此操作。 link 必须像下面这样才能正确打开带有跨多行的预填充消息的 WhatsApp 聊天:

<?php
    $msg = "First line\r\nSecond line\r\n\r\nThird line\r\nFourth line";
    $msg = str_replace("\r\n", urlencode("\r\n"), $msg); // note the double quotes

    echo "<a href='whatsapp://send?text=$msg'>Share on WhatsApp</a>";
?>

现在,如果有人在他的 Android 或 iOS 设备上浏览您的网站时单击 link,则 WhatsApp 应用程序将打开以允许他选择联系人,并且使用将跨越多行的指定文本预填充输入字段,如下所示:

First line
Second line

Third line
Fourth line

请注意,必须使用双引号,即 "\r\n" 而不是 '\r\n'

虽然 urlencode($msg) 适用于大多数移动浏览器,但它在 android 设备上的 firefox 中使用 + 对空格进行编码,因此您的用户可能会看到像 Text+on+the+first+line 这样的文本。更好的解决方法是使用 rawurlencode($msg) 以使其与所有浏览器兼容,因为它会强制根据 RFC 3986 格式对文本进行编码。