php阿里大于thinkphp5基本配置与使用

来源:互联网 发布:mobi编辑软件 编辑:程序博客网 时间:2024/06/07 05:26
<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Send;
class Index extends Controller{

/*
*发送短信阿里大于
*/
   public function sms()
{

$Send = new Send;
$result = $Send->sms([
'param'  => ['number'=>'123456','product'=>'惯性给力'],
'mobile'  => "15860162181",
'template'  => 'SMS_67575195',
]);
if($result !== true){
echo('短信没有发送成功');

}else{
echo('短信下发成功!');
}

}

}

然后在model中创建一个Send.php文件代码如下

<?php
namespace app\index\model;
use think\Model;
use think\Validate;
use note\sms\TopClient;
use note\sms\AlibabaAliqinFcSmsNumSendRequest;
use note\sms\RequestCheckUtil;
use note\sms\Resultset;
use note\sms\TopLogger;
class Send extends Model
{
public static $sms_config = [
'appkey' => '****',//阿里大于APPKEY
'secretKey' => '****',//阿里大于secretKey
'FreeSignName' => '惯性给力',//短信签名
];
public function sms($data=[])
{
$validate = new Validate([
['param','require|array','参数必填|参数必须为数组'],
['mobile','require|/1[34578]{1}\d{9}$/','手机号错误|手机号错误'],
['template','require','模板id错误'],
]);
if (!$validate->check($data)) {
return $validate->getError();
}
$config = self::$sms_config;

$c = new TopClient;
$c->appkey = $config['appkey'];
$c->secretKey = $config['secretKey'];
$req = new AlibabaAliqinFcSmsNumSendRequest;


$req->setExtend('');
$req->setSmsType('normal');
$req->setSmsFreeSignName($config['FreeSignName']);
$req->setSmsParam(json_encode($data['param']));
$req->setRecNum($data['mobile']);
$req->setSmsTemplateCode($data['template']);
$result = $c->execute($req);
$result = $this->_simplexml_to_array($result);
if(isset($result['code'])){
return $result['sub_code'];
}
return true;
}


private function _simplexml_to_array($obj)
{//该函数用于转化阿里大于返回的数据,将simplexml格式转化为数组,方面后续使用
if(count($obj) >= 1){
$result = $keys = [];
foreach($obj as $key=>$value){
isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);
if( $keys[$key] == 1 ){
$result[$key] = $this->_simplexml_to_array($value);
}elseif( $keys[$key] == 2 ){
$result[$key] = [$result[$key], $this->_simplexml_to_array($value)];
}else if( $keys[$key] > 2 ){
$result[$key][] = $this->_simplexml_to_array($value);
}
}
return $result;
}else if(count($obj) == 0){
return (string)$obj;
}
}
}
?>

其中需要引入五个文件,也就是阿里大于的SDK中的

TopClient.php
AlibabaAliqinFcSmsNumSendRequest.php
RequestCheckUtil.php
Resultset.php
TopLogger.php

然后分别在每个文件中加入命名空间

我是把这几个文件放在extend\note\sms中

命名空间需要加入 namespace note\sms;即可剩下的短信验证就简单了。

在模板阿里大于中的验证码模板     验证码${number}