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