SendSms.php 2.87 KB
<?php

namespace WebPlugin;
/**
 * 发送短信
 */
class SendSms
{
    private static $url = '//www.ztsms.cn/sendSms.do';
    private static $username = 'youhuo';
    private static $password = '22b5d8454c5cea4d972b1b4958227d8f';
    private static $productid = '333333';

    protected static $code = array(
        '-1' => '用户名或者密码不正确或用户禁用或者是管理账户',
        '1' => '发送短信成功',
        '0' => '发送短信失败',
        '2' => '余额不够或扣费错误',
        '3' => '扣费失败异常',
        '5' => '短信定时成功',
        '6' => '有效号码为空',
        '7' => '短信内容为空',
        '8' => '无签名,必须,格式:【签名】',
        '9' => '没有Url提交权限',
        '10' => '发送号码过多,最多支持2000个号码',
        '11' => '产品ID异常或产品禁用',
        '12' => '参数异常',
        '15' => 'Ip验证失败',
        '19' => '短信内容过长,最多支持500个,或提交编码异常导致',
    );
    /**
     * 发送普通短信
     * @param type array $mobiles 手机号
     * @param type string $content 内容
     * @return type []
     */
    public static function ordinarySms($mobiles, $content)
    {
        if (empty($mobiles)) {
            return self::$code[6];
        }

        if (empty($content)) {
            return self::$code[7];
        }

        if (is_string($mobiles)) {
            $mobiles = array($mobiles);
        }

        $mobiles = array_unique($mobiles);

        $data = array(
            'mobile' => implode(',', $mobiles),
            'content' => $content
        );

        $result = self::post($data);

        if (isset($result[0]) && $result[0] * 1 === 1) {
            return array('code' => 200, 'msg' => self::$code[$result[0]]);
        }

        return array('code' => 400, 'msg' => isset(self::$code[$result[0]]) ? self::$code[$result[0]] : '发送失败');
    }
    
    private static function post($data = array(), $timeout = 50)
    {
        $ch = curl_init(self::$url);
        $data['username'] = self::$username;
        $data['password'] = self::$password;
        $data['productid'] = self::$productid;
        $data['content'] = $data['content'];

        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 YOHOWEB');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);

        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, null, '&'));
        }

        $result = curl_exec($ch);

        if (!empty($result)) {
            $result = explode(',', $result);
        }

        curl_close($ch);
        unset($ch, $data);

        return $result;
    }
}