With the development of the Internet, text messaging has become an indispensable part of our lives. In the modern business world, text messaging is also becoming more and more important because it is a fast, convenient, and low-cost communication method that allows companies to communicate with customers in real time. However, as the scale of enterprises gradually expands, manually sending text messages can no longer meet the needs. Therefore, the function of automatically sending text messages has become more and more important.
PHP is a popular server-side scripting language that is ideal for handling web requests. This article will introduce how to use PHP to automatically send text messages.
First of all, we need to understand some basic principles and processes of automatically sending text messages. In the process of automatically sending SMS messages, we need the following three basic elements: SMS gateway, SMS interface and SMS content.
In the process of automatically sending text messages, the SMS gateway is an indispensable part. SMS gateway is a middleware that connects SMS senders and receivers. It implements the sending and receiving of SMS messages. When choosing an SMS gateway, we should pay attention to the following factors: SMS sending speed, compatibility, price, security and stability.
The SMS interface is the communication interface between the server and the SMS gateway. It is responsible for communicating between the instructions on the server and the SMS gateway, and sending the SMS to the correct recipient. SMS interfaces are usually divided into two categories: HTTP interface and SDK interface. The HTTP interface has the advantages of strong compatibility, simple use, and high stability, and is suitable for small business scenarios; the SDK interface is more flexible, highly secure, and suitable for large and complex business scenarios.
SMS content refers to the text message to be sent. When writing text message content, you should pay attention to the following aspects: A good text message content should be able to attract the user's attention and convey the correct information in a short text.
After understanding the basic elements, we can start writing PHP code to automatically send text messages.
First of all, we need to choose an SMS gateway and SMS interface. Here we take the Alibaba Cloud SMS service as an example and implement it using the HTTP interface of the Alibaba Cloud SMS service. The specific steps are as follows:
// The following variables are required, please log in to Alibaba Cloud to obtain
$accessKeyId = "XXXXXXXXXXX";
$accessKeySecret = "XXXXXXXXXX";
$signName = "XXXXXXXXXX";
$templateCode = "XXXXXXXXXXX";
$phoneNumbers = "XXXXXXXXXXX"; // Mobile phone number to receive text messages
$templateParam = array (
"code" => mt_rand(100000, 999999) // 短信模板中的替换参数,这里使用PHP内置函数mt_rand()生成一个6位验证码</p> <p>);</p> <p>//Send SMS interface<br>function sendSms($accessKeyId, $accessKeySecret, $phoneNumbers, $signName, $templateCode, $templateParam)<br> {</p> <pre class="brush:php;toolbar:false">$params = array (); // *** 需用户填写部分 *** // fixme 必填: 短信接收号码 $params["PhoneNumbers"] = $phoneNumbers; // fixme 必填: 短信签名-可在短信控制台中找到 $params["SignName"] = $signName; // fixme 必填: 短信模板-可在短信控制台中找到 $params["TemplateCode"] = $templateCode; // fixme 可选: 模板中的变量替换JSON串 if ($templateParam) { $params["TemplateParam"] = json_encode($templateParam); } // *** 需用户填写部分结束, 以下代码若无必要无需更改 *** if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) { $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE); } // 初始化SignatureHelper实例用于设置参数,签名以及发送请求 $helper = new SignatureHelper(); try { $content = $helper->request( $accessKeyId, $accessKeySecret, "dysmsapi.aliyuncs.com", array_merge($params, array( "RegionId" => "cn-hangzhou", "Action" => "SendSms", "Version" => "2017-05-25", )) ); return $content; } catch (Exception $e) { return false; }
}
// Signature class
class SignatureHelper {
/** * 生成签名并发起请求 * * @param string $accessKeyId * 您的Access Key ID * @param string $accessKeySecret * 您的Access Key Secret * @param string $domain * API接口所在域名 * @param array $params * 参数结构 * @param string $method * 请求方式,GET或POST * @return bool|\mixed 服务器返回的数据,失败返回false */ public function request($accessKeyId, $accessKeySecret, $domain, $params, $method = 'POST') { $apiParams = array (); foreach ($params as $key => $value) { $apiParams[$key] = $value; } // 添加公共请求参数 $apiParams["SignatureMethod"] = "HMAC-SHA1"; $apiParams["SignatureNonce"] = uniqid(mt_rand(0, 0xffff), true); $apiParams["SignatureVersion"] = "1.0"; $apiParams["AccessKeyId"] = $accessKeyId; $apiParams["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z"); $apiParams["Format"] = "JSON"; // 计算签名并拼接请求参数 ksort($apiParams); $canonicalizedQueryString = ''; foreach ($apiParams as $key => $value) { $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value); } $stringToSign = $method . '&%2F&' . $this->percentEncode(substr($canonicalizedQueryString, 1)); $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true)); $apiParams["Signature"] = $signature; // 发送请求 $url = 'http://' . $domain . '/?' . http_build_query($apiParams); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $content = curl_exec($ch); curl_close($ch); return $content; } /** * 生成规范化请求字符串 * * @param array $params * 请求参数 * @return string */ private function getCanonicalizedQueryString(array $params) { ksort($params); $canonicalizedQueryString = ''; foreach ($params as $key => $value) { $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value); } return substr($canonicalizedQueryString, 1); } /** * 生成规范化请求 * * @param array $params * 请求参数 * @return string */ private function getCanonicalizedHeaders(array $params) { ksort($params); $canonicalizedHeaders = ''; foreach ($params as $key => $value) { $canonicalizedHeaders .= $key . ':' . $value . "\n"; } return $canonicalizedHeaders; } /** * 获取content-Md5值 * * @param string $content * 请求内容 * @return string */ private function getContentMd5($content) { return base64_encode(md5($content, true)); } /** * 特殊字符编码 * * @param string $value * 需要编码的字符串 * @return string */ private function percentEncode($value) { $value = urlencode($value); $value = preg_replace('/\+/', '%20', $value); $value = preg_replace('/\*/', '%2A', $value); $value = preg_replace('/%7E/', '~', $value); return $value; }
}
// Call the send SMS interface
$result = sendSms($accessKeyId, $accessKeySecret, $phoneNumbers, $signName, $templateCode, $templateParam);
if ($result !== false) {
echo "验证码已发送成功";
} else {
echo "验证码发送失败";
}
The above PHP code implements the function of sending text messages using the HTTP interface of Alibaba Cloud SMS Service. We can make appropriate adjustments and modifications as needed to meet specific business needs.
In short, it is very useful to realize the function of automatically sending text messages. By learning the relevant knowledge and technologies introduced in this article, we can easily implement the function of automatically sending text messages and improve our work efficiency and business level.
The above is the detailed content of php implements automatic text messaging. For more information, please follow other related articles on the PHP Chinese website!