laravel项目需要用到短信渠道,使用phpsms发送短信,但是项目中接的短信渠道并不是phpsms默认支持的,需要修改代理器,phpsms支持两种自定义代理器,一种是自定义代理器,一种是寄生代理器,由于本人是php小白,没看懂官方的自定义代理器(继承Toplan\PhpSms\Agent类,实现接口)所以就按照官网的例子稍微改了改
下面以鼎信短信接入为例
第一步在发送短信的地方设置个scheme
Sms::scheme([
'decentAgent' => [
'20 backup',
'sendTemplateSms' => function($agent, $to, $tmpId, $tmpData){
// 获取配置(如果设置了的话):
// $key = $agent->key;
// 可使用的内置方法:
$params = array(
'mobile' => $to,
'param' => 'code:'.$tmpData['code'],
'tpl_id' => $tmpId,
);
$config = $agent->config;// 获取代理的配置
$headers = array(
CURLOPT_HTTPHEADER => array(
'Authorization:APPCODE ' . $config['appCode'],
),
CURLOPT_HEADER => true,
);
$rsp = $agent->curlPost($config['url'], $params, $headers); //post请求
Log::debug($rsp);
$pattern = '/(?<=\{)[^\}]+/';
$arrMatches = [];
preg_match($pattern, $rsp['response'], $arrMatches);
Log::debug($arrMatches);
$result = '{'.$arrMatches[0].'}';
Log::debug($result);
if (json_decode($result)->return_code !== '00000')
{
throw new OuterException('短信发送失败');
}
// 更新发送结果:
$agent->result(Agent::SUCCESS, true);
$agent->result(Agent::INFO, 'some info');
$agent->result(Agent::CODE, 'your code');
},
]
]);
2、设置配置信息
Sms::config([
'decentAgent' => [
'url' => $aliyunDecent['url'],
'appCode' => $aliyunDecent['appCode'],
'tpl_id' => $aliyunDecent['tpl_id'],
],
]);
3、发送
$status = Sms::make()->to($to)->template('decentAgent', $aliyunDecent['tpl_id'])->data($data)
->send();
to template data 是sendTemplateSms方法的参数
'sendTemplateSms' => function($agent, $to, $tmpId, $tmpData){}
如果是内容短信只需要传入内容content即可
类库Agent.php中根据内容或模版是否为空来判断发送哪种短信,下面是判断代码
public function sendSms($to, $content = null, $tempId = null, array $data = [], array $params = [])
{
$this->reset();
$this->params($params, true);
$to = $this->formatMobile(Util::formatMobiles($to));
if ($tempId && $this instanceof TemplateSms) {
$this->sendTemplateSms($to, $tempId, $data);
} elseif ($content && $this instanceof ContentSms) {
$this->sendContentSms($to, $content);
}
}
4、在config/phpsms.php文件中配置scheme 和config
'scheme' => [
// 'Log',
'decentAgent',
],
'decentAgent' => [
'url' => 'http://',
'appCode' => 'xxxx',
'tpl_id' => 'xxxx',
],
四步完成即可发送短信
路过的大神有谁会自定义代理器的望指教,php初级伤不起
参考链接:https://github.com/toplan/phpsms#%E5%AF%84%E7%94%9F%E4%BB%A3%E7%90%86%E5%99%A8