PHP控制阿里云短信API接口实现短信群发功能

时间:2023-03-08 21:52:37

阿里云短信支持先使用后支付的原则,价格为4分半1条。

PHP控制阿里云短信API接口实现短信群发功能

通过SDK可以与网站功能的绑定,实现响应的短信发送功能

PHP控制阿里云短信API接口实现短信群发功能

现已统一合并升级为:消息服务。

PHP控制阿里云短信API接口实现短信群发功能

消息服务

阿里云消息服务(Message Service,简称 MNS)是一种高效、可靠、安全、便捷、可弹性扩展的分布式消息服务。MNS能够帮助应用开发者在他们应用的分布式组件上*的传递数据、通知消息,构建松耦合系统。

新的SDK下载地址:

Java SDK:https://help.aliyun.com/document_detail/51063.html
Python SDK:https://help.aliyun.com/document_detail/51372.html
C# SDK:https://help.aliyun.com/document_detail/52016.html
PHP SDK:https://help.aliyun.com/document_detail/51929.html

如果你像我一样是以前申请的短信服务升级过来的,那么旧的接口与API仍然能使用,新申请的只能使用新的SDK了。

本文旨在通过PHP实现阿里云短信接口,摆脱繁琐的SDK。

短信界面通过表单方式实现。

<div style="width:90%;margin:auto;margin-top:100px;text-align:center;font-size:12px;color:#192E32;">
<form method="post" action="">
<b>模板CODE:</b>&nbsp;&nbsp;<input type="text" name="tcode" id="tcode" required="required" value="SMS_12345678"
onFocus="if(value==defaultValue){value='';this.style.color='#000'}" onBlur="if(!value){value=defaultValue;this.style.color='#999'}"
oninput="myinput()" onpropertychange="myclick()" style="color:#999999;height:26px; width:150px; line-height:26px;" />
<span class="error" style="color:red;">&nbsp;&nbsp;阿里云短信模板编号</span>
<br><br>
<b>用户类型:</b>
<input type="radio" name="tuser" id="tuser" value="suppliers" checked="checked"; />供应商
<input type="radio" name="tuser" id="tuser" value="users" />全部用户
<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
<br><br>
<input type="submit" name="sub" id="sub" value="发送短信" disabled="true" />
</form>
</div>
<script type="text/javascript">
function myinput(){
if(document.getElementById("tcode").value){
document.getElementById("sub").removeAttribute("disabled");
}
else{
document.getElementById("sub").setAttribute("disabled",disabled);
}
};
function myclick(){
if(document.getElementById("tcode").value){
document.getElementById("sub").setAttribute("disabled",false);
}
else{
document.getElementById("sub").setAttribute("disabled",true);
}
};
</script>

注意:阿里云短信模板编号为SMS_形式,通过JS控制输入提交按钮是否可用。

PHP控制阿里云短信API接口实现短信群发功能

<?php

define('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

https://ak-console.aliyun.com/#/accesskey/

YourSignName 和 YourSMSTemplateCode 获取在阿里云控制台消息服务。

PHP控制阿里云短信API接口实现短信群发功能