<?php
/**
 * 手机短信类
 */

namespace chuanglan;

use think\facade\Log;

class Chuanglan
{

    /**
     * 创蓝短信
     * @param $mobile
     * @param $smslog_param
     * @return array
     */
    public function send($mobile, $smslog_param)
    {
        $appkey = config('mobile.sms_chuanglan_appkey');
        $secret = config('mobile.sms_chuanglan_secret');
        if (empty($appkey) || empty($secret)) {
            return ['code' => 1, 'msg' => '请绑定模板参数'];
        }

        if (empty($smslog_param['params'])) {
            $url = 'http://smssh1.253.com/msg/send/json';
            //创蓝接口参数
            $postArr = [
                'account'  => $appkey,
                'password' => $secret,
                'msg'      => $smslog_param['message'],
                'phone'    => $mobile,
                'report'   => 'true',
            ];
        } else {
            $params_str = $mobile . ',' . implode(',', $smslog_param['params']);
            $url        = 'http://smssh1.253.com/msg/variable/json';
            //创蓝接口参数
            $postArr = [
                'account'  => $appkey,
                'password' => $secret,
                'msg'      => $smslog_param['message'],
                'params'   => $params_str,
                'report'   => 'true',
            ];
        }
        $postFields = json_encode($postArr);
        $ch         = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json; charset=utf-8'   //json版本需要填写  Content-Type: application/json;
            ]
        );
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); //若果报错 name lookup timed out 报错时添加这一行代码
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($ch);
        curl_close($ch);
        $rsp = json_decode($ret, true);

        if ($rsp['code'] != 0) {
            Log::error('短信发送失败：' . json_encode($rsp) . "。原始参数：" . json_encode($postArr));
            return ['code' => 1, 'msg' => $rsp['errorMsg']];
        } else {
            return ['code' => 0];
        }
    }
}
