Sms.php
<?php
class Sms{
private $_error = [];
//发送短信
public function send($api_url,$send_data){
$res_data = $this->http_post($api_url,$send_data);
return json_decode($res_data, true);
}
//获取access_token
public function getAccessToken($api_url,$param){
$res_data = $this->http_post($api_url,$param);
return json_decode($res_data, true);
}
//发送post请求
private function http_post($api_url = '', $param = []) {
$ch = curl_init();
if (0 === strpos(strtolower($api_url), 'https')) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$headers = ['Content-type: application/json;charset=utf-8',
'Accept: application/json'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));
$res = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
$this->_error[] = $error;
return FALSE;
}
return $res;
}
public function error_msg(){
return $this->_error;
}
}
sendSms.php
<?php
require 'Sms.php';
//appKey 应用标识,添加应用成功后应用的唯一标识
$sms = new Sms();
$token_url = 'https://api.chuangcache.com/OAuth/authorize';
$token_params = [
'appid' => 'appid',
'appsecret' => 'appsecret',
'grant_type' => 'client_credentials'
];
$result = $sms->getAccessToken($token_url, $token_params);
$access_token = '';
if (isset($result['status']) && $result['status'] == 1) {
$access_token = $result['data']['access_token'];
$expires_in = $result['data']['expires_in'];//access_token的生命周期,单位是秒数。过期之后要重新获取
}
$send_data = [
'app_key' => 'app_key',
'mobile' => 'mobile',
'content' => '你的验证码是403763,此验证码用于登录。10秒钟之内有效',
'access_token' => $access_token,
'time' => time() * 1000
];
$sms_url = 'http://sms.chuangcache.com/api/sms/ordinary';
//
////发送短信
$res_data = $sms->send($sms_url, $send_data);
//
if ($res_data) {
if (isset($res_data['code']) && $res_data['code'] == 1000) {
echo 'success'.$res_data['sendid'];
} else {
echo 'failed,code:' . $res_data['code'] . ',msg:' . $res_data['msg'];
}
} else {
var_dump($sms->error_msg());
}
exit;