Detailed explanation of Alibaba Cloud SMS service
阿里云短信支持先使用后支付的原则,价格为4分半1条。
通过SDK可以与网站功能的绑定,实现响应的短信发送功能
现已统一合并升级为:消息服务。
消息服务
阿里云消息服务(Message Service,简称 MNS)是一种高效、可靠、安全、便捷、可弹性扩展的分布式消息服务。MNS能够帮助应用开发者在他们应用的分布式组件上自由的传递数据、通知消息,构建松耦合系统。
新的SDK下载地址:
Java SDK:
Python SDK:
C# SDK:
PHP SDK:
如果你像我一样是以前申请的短信服务升级过来的,那么旧的接口与API仍然能使用,新申请的只能使用新的SDK了。
本文旨在通过PHP实现阿里云短信接口,摆脱繁琐的SDK。
短信界面通过表单方式实现。
模板CODE: 阿里云短信模板编号 用户类型:
注意:阿里云短信模板编号为SMS_形式,通过JS控制输入提交按钮是否可用。
<?phpdefine('IN_ECS', true);require(dirname(__FILE__) . '/includes/init.php');//ECShop初始化页面文件 function https_request($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($curl); if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);} curl_close($curl); return $data; } function xml_to_array($xml){ $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/"; if(preg_match_all($reg, $xml, $matches)){ $count = count($matches[0]); for($i = 0; $i < $count; $i++){ $subxml= $matches[2][$i]; $key = $matches[1][$i]; if(preg_match( $reg, $subxml )){ $arr[$key] = xml_to_array( $subxml ); }else{ $arr[$key] = $subxml; } } } return @$arr; } function random($length = 6 , $numeric = 0) { PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000); if($numeric) { $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1)); } else { $hash = ''; $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz'; $max = strlen($chars) - 1; for($i = 0; $i < $length; $i++) { $hash .= $chars[mt_rand(0, $max)]; } } return $hash; } $target = "https://sms.aliyuncs.com/?"; //阿里云短信请求地址头 $mobile_code = random(6,1); function percentEncode($str) { // 使用urlencode编码后,将"+","*","%7E"做替换即满足ECS API规定的编码规范 $res = urlencode($str); $res = preg_replace('/\+/', '%20', $res); $res = preg_replace('/\*/', '%2A', $res); $res = preg_replace('/%7E/', '~', $res); return $res; } function computeSignature($parameters, $accessKeySecret) { // 将参数Key按字典顺序排序 ksort($parameters); // 生成规范化请求字符串 $canonicalizedQueryString = ''; foreach($parameters as $key => $value) { $canonicalizedQueryString .= '&' . percentEncode($key) . '=' . percentEncode($value); } // 生成用于计算签名的字符串 stringToSign $stringToSign = 'GET&%2F&' . percentencode(substr($canonicalizedQueryString, 1)); //echo "<br>".$stringToSign."<br>"; // 计算签名,注意accessKeySecret后面要加上字符'&' $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true)); return $signature; } // 注意使用GMT时间 date_default_timezone_set("GMT"); $dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范 $accessKeyId = '根据实际修改'; // 这里填写您的Access Key ID $accessKeySecret = '根据实际修改'; // 这里填写您的Access Key Secret $ParamString="{\"code\":\"".strval($mobile_code)."\"}"; // 发送请求 if($_REQUEST['act'] == 'aliyun_mns'){// POST表单提交请求页面动作?act=aliyun_mns/* 显示模板 */if (isset($_POST['tcode']) && isset($_POST['tuser'])) {$tcode=$_POST["tcode"];// 表单提交SMS短信模板$tuser=$_POST["tuser"]; //表单提交用户组 $sql = "SELECT DISTINCT mobile_phone FROM " .$ecs->table($tuser);$phoneNO = $db->getCol($sql);$ii=0;foreach($phoneNO as $key=>$pn) {if(preg_match("/^1[34578]\d{9}$/",$pn)){$data = array( // 公共参数 'SignName'=>'根据实际修改', 'Format' => 'XML', 'Version' => '2016-09-27', 'AccessKeyId' => $accessKeyId, 'SignatureVersion' => '1.0', 'SignatureMethod' => 'HMAC-SHA1', 'SignatureNonce'=> uniqid(), 'Timestamp' => date($dateTimeFormat), // 接口参数 'Action' => 'SingleSendSms', 'TemplateCode' =>$tcode, 'RecNum' => $pn, 'ParamString' => $ParamString ); $data['Signature'] = computeSignature($data, $accessKeySecret);//给每一位用户发短信 $result = xml_to_array(https_request($target.http_build_query($data))); } }} /* 显示Smarty模板 */assign_query_info();$smarty->display('aliyun_mns.htm'); } ?>
创建和查看Access Key
YourSignName 和 YourSMSTemplateCode 获取在阿里云控制台消息服务。
The above is the detailed content of Detailed explanation of Alibaba Cloud SMS service. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
