阿里云发送短信

直接使用阿里云短信API发送短信,阿里云短信发送的最小SDK实现

官网API文档地址: https://helpcdn.aliyun.com/document_detail/102715.html

define('DebugModel', true);
define('AccessKeyId', 'AccessKeyId');
define('AccessKeySecret', 'AccessKeySecret');
define('SignName', '蘑菇博客');
define('TemplateCode', 'SMS_123456789');
define('TemplateParam', ['code' => '123456',]);

/**
 *  获取签名
 */
function getSign($add)
{
    $data = array(
        "RegionId" => "cn-hangzhou",
        "Action" => "SendSms",
        "Version" => "2017-05-25",
        "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",
    );
    $data = array_merge($data, $add);
    ksort($data);
    $format = http_build_query($data);
    $signUrl = 'GET&%2F&' . urlencode(str_replace(['+', '*', '%7E'], ['%20', '%2A', '~'], $format));
    $sign = urlencode(base64_encode(hash_hmac('sha1', $signUrl, AccessKeySecret . '&', true)));
    return array('url' => $format, 'sign' => $sign);
}

/**
 *  发送短信
 */
function sendSMS($phone)
{
    $sign = getSign(['PhoneNumbers' => $phone, 'SignName' => SignName, 'TemplateCode' => TemplateCode, 'TemplateParam' => json_encode(TemplateParam)]);
    $url = 'https://dysmsapi.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    $request = json_decode(httpRequest($url));
    if (isset($request->Code) && $request->Code == 'OK') {
        return true;
    } else {
        if (DebugModel) {
            var_dump($request);
        }
        return false;
    }
}

/**
 *  发起 HTTP 请求
 */
function httpRequest($url)
{
    $header = array(
        'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
        'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding: gzip, deflate',
        'Connection: close',
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);
    if ($error) {
        return $error;
    } else {
        return $data;
    }
}

function main()
{
    $phones = ['18612345678'];
    foreach ($phones as $v) {
        if (sendSMS($v)) {
            echo $v, " send SMS success! \n";
        } else {
            echo $v, " send SMS failed! \n";
        }
    }
}

main();