tpshop 阿里云短信sdk使用和带链接短信实现

来源:互联网 发布:php 判断是否刷新页面 编辑:程序博客网 时间:2024/06/08 01:13

tpshop 阿里云短信sdk使用

  • 创建keyId 和 keysecret,下载sdk
    先去阿里云申请账号(后台地址: https://www.aliyun.com/ , 注意不是阿里大于短信平台),登入控制台,创建得到keyId 和 keysecret.从阿里云短信官网下载SDK(https://help.aliyun.com/document_detail/32381.html?spm=5176.doc51929.6.669.NaKJRQ)本人使用的版本是Version 1.3.5更新日期是2017-06-06 将SDK放到thinkphp框架的vendor目录下, 如下图:
  • 申请短信模板及其签名
    测试好几次发现模板的参数值不能带“.”,刚开始没收到短信还以为调用sdk的问题,折腾了一天才发现是换个模板就好了
    申请短信模板及其签名
  • 发送短信类
    \Application\Common\Util\PublishBatchSMSMessageDemo.class.php
    以下代码分别修改
    • YourMNSEndpoint
    • YourAccessId
    • YourAccessKey
    • YourTopicName
    • YourSMSSignName
    • YourSMSTemplateCode
    • YourSMSTemplateParamKey1
<?phpnamespace Common\Util;require_once('/ThinkPHP/Library/Vendor/mns-autoloader.php');use AliyunMNS\Client;use AliyunMNS\Topic;use AliyunMNS\Constants;use AliyunMNS\Model\MailAttributes;use AliyunMNS\Model\SmsAttributes;use AliyunMNS\Model\BatchSmsAttributes;use AliyunMNS\Model\MessageAttributes;use AliyunMNS\Exception\MnsException;use AliyunMNS\Requests\PublishMessageRequest;class PublishBatchSMSMessageDemo{    public function run($mobilephone,$sendurl)    {        /**         * Step 1. 初始化Client         */        $this->endPoint = "YourMNSEndpoint"; // eg. http://1234567890123456.mns.cn-shenzhen.aliyuncs.com        $this->accessId = "YourAccessId";        $this->accessKey = "YourAccessKey";        $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);        /**         * Step 2. 获取主题引用         */        $topicName = "YourTopicName";        $topic = $this->client->getTopicRef($topicName);        /**         * Step 3. 生成SMS消息属性         */        // 3.1 设置发送短信的签名(SMSSignName)和模板(SMSTemplateCode)        $batchSmsAttributes = new BatchSmsAttributes("YourSMSSignName", "YourSMSTemplateCode");        // 3.2 (如果在短信模板中定义了参数)指定短信模板中对应参数的值        $batchSmsAttributes->addReceiver($mobilephone, array("YourSMSTemplateParamKey1" => $sendurl));        // $batchSmsAttributes->addReceiver("YourReceiverPhoneNumber2", array("YourSMSTemplateParamKey1" => "value1"));        $messageAttributes = new MessageAttributes(array($batchSmsAttributes));        /**         * Step 4. 设置SMS消息体(必须)         *         * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。         */         $messageBody = "smsmessage";        /**         * Step 5. 发布SMS消息         */        $request = new PublishMessageRequest($messageBody, $messageAttributes);        try        {            $res = $topic->publishMessage($request);            echo $res->isSucceed();            echo "\n";            echo $res->getMessageId();            echo "\n";        }        catch (MnsException $e)        {            echo $e;            echo "\n";        }    }} ?>
  • Controller里面调用发送短信类
function testsms(){         $instance = new \Common\Util\PublishBatchSMSMessageDemo();        $instance->run("13810545296","Public/Uploads/Phototouch/0MmJRb5ZmT5z7HLnSYYc/tour.html");    }