申请accesskey
获取到Accesskey ID和Accesskey Secret保存下来,一会要用到
添加测试手机号,在接口测试能否正常发送
下载阿里云短信sdk,使用composer下载,没有安装请先安装
安装可以安装到任意文件夹下,后面代码写好后,直接复制到tp项目内就行,最新版本安装可能composer查找不到,所以我这里安装2.0.20
composer require alibabacloud/dysmsapi-20170525 2.0.20
安装完成后文件目录结构
新建src文件夹,在里面创建一个类Sample,复制如下代码
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Sample;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
class Sample {
/**
* 使用AK&SK初始化账号Client
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Dysmsapi Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
$config = new Config([
// 必填,您的 AccessKey ID
"accessKeyId" => $accessKeyId,
// 必填,您的 AccessKey Secret
"accessKeySecret" => $accessKeySecret
]);
// 访问的域名
$config->endpoint = "dysmsapi.aliyuncs.com";
return new Dysmsapi($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($phone,$code){
// 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/311677.html
$client = self::createClient("填第一步的Accesskey ID", "填第一步的Accesskey Secret");
$sendSmsRequest = new SendSmsRequest([
"signName" => "阿里云短信测试",
"templateCode" => "SMS_154950909",
"phoneNumbers" => "$phone",
"templateParam" => "{\"code\":\"$code\"}"
]);
$runtime = new RuntimeOptions([]);
try {
// 复制代码运行请自行打印 API 的返回值
$data=$client->sendSmsWithOptions($sendSmsRequest, $runtime);
echo json_encode($data);
}
catch (Exception $error) {
if (!($error instanceof TeaError)) {
$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
}
// 如有需要,请打印 error
Utils::assertAsString($error->message);
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
//Sample::main(array_slice($argv, 1));
演示调用(到这里我们的接口就已经接好了,现在调用Sample类的main方法就能发送短信了)
原生调用:在src文件夹下新建一个index.php ,访问index.php。传入参数56789就调用成功了
<?php
include "Sample.php";
if($_POST['sms']==56789){
$phone=$_POST['phone'];
$code=rand(100000,999999);
$data=[
'phone'=>$phone,
'code'=>$code
];
\AlibabaCloud\SDK\Sample\Sample::main($phone,$code);
}
?>
thinkphp调用:
(一)将cmsPhp文件夹移到tp6项目public文件夹下
(2)新建控制器Code
Code.php代码
<?php
namespace app\controller;
include "./cmsPhp/src/Sample.php";
use AlibabaCloud\SDK\Sample\Sample;
use think\facade\Db;
class Code
{
public function code2(){
if($_POST['sms']==56789){
$phone=$_POST['phone'];
$code=rand(100000,999999);
$date=Date('Y-m-d H:i:s');
$data=[
'phone'=>$phone,
'code'=>$code,
'date'=>$date
];
$suc=Db::table('code')->save($data);
Sample::main($phone,$code);
}
}
}
访问code2方法传入手机号就调用成功了