/**
* 阿里云 短信验证
* @param $phone 手机号码
* @param null $mobile_code 验证码
* @param null $template_code 短信模版
*/
public function phoneCode($phone,$mobile_code=null,$template_code=null){
if (!$mobile_code){$mobile_code = $this->random(6,1);}
if(!$template_code){$template_code='SMS_37650042';}
$target = "https://sms.aliyuncs.com/?";
// 注意使用GMT时间
date_default_timezone_set("GMT");
$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范
$accessKeyId = 'LTAIGsgBVt8MDTyf'; // 这里填写您的Access Key ID
$accessKeySecret = '5koNqwSpKi0SfjfyHUWqF0lCLIwuoS'; // 这里填写您的Access Key Secret
$ParamString="{\"code\":\"".strval($mobile_code)."\",\"time\":\"15\"}";
$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' => $template_code,
'RecNum' => $phone,
'ParamString' => $ParamString
);
// 计算签名并把签名结果加入请求参数
//echo $data['Version']."<br>";
//echo $data['Timestamp']."<br>";
$data['Signature'] = $this->computeSignature($data, $accessKeySecret);
// 发送请求
$result = $this->xml_to_array($this->https_request($target.http_build_query($data)));
print_r($result);
}
public 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;
}
public 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] = $this->xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return @$arr;
}
public 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';*/
$chars = '0123456789';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
}
return $hash;
}
public 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;
}
public function computeSignature($parameters, $accessKeySecret)
{
// 将参数Key按字典顺序排序
ksort($parameters);
// 生成规范化请求字符串
$canonicalizedQueryString = '';
foreach($parameters as $key => $value)
{
$canonicalizedQueryString .= '&' . $this->percentEncode($key)
. '=' . $this->percentEncode($value);
}
// 生成用于计算签名的字符串 stringToSign
$stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
//echo "<br>".$stringToSign."<br>";
// 计算签名,注意accessKeySecret后面要加上字符'&'
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
return $signature;
}
第二种方式:
导入项目中 如图
源码如下
<?php
ini_set("display_errors", "on");
require_once dirname(__DIR__) . '/sms/vendor/autoload.php';
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
// 加载区域结点配置
Config::load();
/**
* Class SmsDemo
*
* Created on 17/10/17.
* 短信服务API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过
* 执行此文件即可体验语音服务产品API功能(只需要将AK替换成开通了云通信-短信服务产品功能的AK即可)
* 备注:Demo工程编码采用UTF-8
*/
class Sms
{
static $acsClient = null;
/**
* 取得AcsClient
*
* @return DefaultAcsClient
*/
public static function getAcsClient() {
//产品名称:云通信流量服务API产品,开发者无需替换
$product = "Dysmsapi";
//产品域名,开发者无需替换
$domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
$accessKeyId = "LTAISVqnlWld4er1"; // AccessKeyId
$accessKeySecret = "MEuXuWz3kN5uN5J0qi7OEk4DFDEPWO"; // AccessKeySecret
// 暂时不支持多Region
$region = "cn-hangzhou";
// 服务结点
$endPointName = "cn-hangzhou";
if(static::$acsClient == null) {
//初始化acsClient,暂不支持region化
$profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
// 增加服务结点
DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
// 初始化AcsClient用于发起请求
static::$acsClient = new DefaultAcsClient($profile);
}
return static::$acsClient;
}
/**
* 发送短信
*
* @param string $signName <p>
* 必填, 短信签名,应严格"签名名称"填写,参考:<a href="https://dysms.console.aliyun.com/dysms.htm#/sign">短信签名页</a>
* </p>
* @param string $templateCode <p>
* 必填, 短信模板Code,应严格按"模板CODE"填写, 参考:<a href="https://dysms.console.aliyun.com/dysms.htm#/template">短信模板页</a>
* (e.g. SMS_0001)
* </p>
* @param string $phoneNumbers 必填, 短信接收号码 (e.g. 12345678901)
* @param array|null $templateParam <p>
* 选填, 假如模板中存在变量需要替换则为必填项 (e.g. Array("code"=>"12345", "product"=>"阿里通信"))
* </p>
* @param string|null $outId [optional] 选填, 发送短信流水号 (e.g. 1234)
* @param string|null $smsUpExtendCode [optional] 选填,上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
* @return stdClass
*/
public static function sendSms($signName,$templateCode, $phoneNumbers, $templateParam = null, $outId = null, $smsUpExtendCode = null) {
// 初始化SendSmsRequest实例用于设置发送短信的参数
$request = new SendSmsRequest();
// 必填,设置雉短信接收号码
$request->setPhoneNumbers($phoneNumbers);
// 必填,设置签名名称
$request->setSignName($signName);
// 必填,设置模板CODE
$request->setTemplateCode($templateCode);
// 可选,设置模板参数
if($templateParam) {
$request->setTemplateParam(json_encode($templateParam));
}
// 可选,设置流水号
if($outId) {
$request->setOutId($outId);
}
// 选填,上行短信扩展码
if($smsUpExtendCode) {
$request->setSmsUpExtendCode($smsUpExtendCode);
}
// 发起访问请求
$acsResponse = static::getAcsClient()->getAcsResponse($request);
// 打印请求结果
var_dump($acsResponse);
return $acsResponse;
}
}
// header('Content-Type: text/plain; charset=utf-8');
// $response = Sms::sendSms(
// "阿里云短信测试专用", //签名
// "SMS_104910077", // 短信模板编号
// "13972235112", // 短信接收者
// Array( // 短信模板中字段的值
// "code"=>"12345",
// "product"=>"dsd"
// ),
// "123" // 流水号,选填
// );