symfony4.2 运用自己封装bundle短信发送功能,刚实验成功

说明:封装的文件 Request.php Sms.php 是阿里的短信平台

效果图:

symfony4.2 运用自己封装bundle短信发送功能,刚实验成功_第1张图片

文件如下目录 标注好了

symfony4.2 运用自己封装bundle短信发送功能,刚实验成功_第2张图片

Request.php

namespace App\Message\SmsBundle\Controller;

class Request
{
    /**
     * 发起请求
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $domain API接口所在域名
     * @param $params API具体参数
     * @param bool $security 使用https
     * @return bool|mixed 返回API接口调用结果,当发生错误时返回false
     */
    public static function initiate($accessKeyId, $accessKeySecret, $domain, $params, $security = false)
    {
        $apiParams = array_merge(array(
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . self::encode($key) . "=" . self::encode($value);
        }

        $stringToSign = "GET&%2F&" . self::encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));

        $signature = self::encode($sign);

        $url = ($security ? 'https' : 'http') . "://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = self::fetchContent($url);
            return json_decode($content);
        } catch (\Exception $e) {
            return false;
        }
    }

    private static function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

    private static function fetchContent($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));

        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if ($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }
}

Sms.php

namespace App\Message\SmsBundle\Controller;

use App\Message\SmsBundle\Controller\Request;

class Sms
{
    /**
     * 短信发送
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param array $params 短信参数
     */
    public static function send($accessKeyId, $accessKeySecret, $params = array())
    {
        try {
            if (empty($params["PhoneNumbers"])) {
                throw new Exception('短信接收号码不能为空');
            }
            if (empty($params["SignName"])) {
                throw new Exception('短信签名不能为空');
            }
            if (empty($params["TemplateCode"])) {
                throw new Exception('短信模板Code不能为空');
            }
            if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
                $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
            }
            $params = array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ));
            $content = Request::initiate(
                $accessKeyId,
                $accessKeySecret,
                "dysmsapi.aliyuncs.com",
                $params
            );
            return (array)$content;
        } catch (Exception $e) {
            $res = array(
                'Code' => 'INVALID_PARAMETERS',
                'Message' => $e->getMessage(),

            );
            return $res;
        }
    }
}

LuckyController.php

/**
 * @Route("lucky/index", name="lucky_index")
 */
public function index()
{
    return $this->render('lucky/index.html.twig');
}
/**
 * @Route("lucky/sendmessage")
 */
public function sendMessage()
{
    $phone = $_POST['phone'];
    $code = $this->generateRandomString(4, [1]);
    $params = array(
        'PhoneNumbers' => $phone,
        'SignName' => '自己设置的签名',
        'TemplateCode' => 'SMS_141580600',
        'TemplateParam' => array(
            'code' => $code
        ),
    );
    $accessKeyId = $this->getParameter('aliyun_accesskey_id');
    $accessKeySecret = $this->getParameter('aliyun_accesskey_secret');
    $res = Sms::send($accessKeyId, $accessKeySecret, $params);
    if ($res['Code'] !== 'OK') {
        $msg = '短信发送失败,请稍候重试';
    }else{
        $msg = '短信发送成功';
    }
    $data = ['msg' => $msg, 'code' => $code];
    return $this->render('lucky/sendmessage.html.twig', $data);
}
public function generateRandomString($length = 6, $type = array(1, 2, 3, 4))
{
    if (!is_array($type)) {
        return false;
    }
    $dec = array();
    if (in_array(1, $type)) {
        array_push($dec, array(48, 57));
    }
    if (in_array(2, $type)) {
        array_push($dec, array(97, 122));
    }
    if (in_array(3, $type)) {
        array_push($dec, array(65, 90));
    }
    if (in_array(4, $type)) {
        array_push($dec, array(33, 47), array(58, 64), array(91, 96), array(123, 126));
    }
    if (empty($dec)) {
        return false;
    }
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomRange = $dec[mt_rand(0, count($dec) - 1)];
        $randomString .= chr(mt_rand($randomRange[0], $randomRange[1]));
    }
    if (empty($randomString)) {
        return false;
    }
    return $randomString;
}

对应的模板

index.html.twig

{% extends 'base.html.twig' %}
{% block body %}
    {{ parent() }}
    
{% endblock %} {% block javascripts%} {{ parent() }} {% endblock %}

发送后返回模板 sendmessage.html.twig

{% extends 'base.html.twig' %}
{% block body %}
    {{ parent() }}
    

{{ msg }}

{{ code }}

{% endblock %}

配置的阿里参数 config/services.yaml

parameters:
    aliyun_accesskey_id: LKKTAIOl6bvrWQcIOO3n
    aliyun_accesskey_secret: A7AgVHRx7WBUU0eMYk9ii273233cV4uAB5Y

你可能感兴趣的:(PHP)