在對接短信之前我們需要拿到下面這些東西
a. 已建立短信應用,擷取APP_Key、APP_Secret和APP接入位址(國際短信還需 擷取通道号)。
b. (僅國内短信)已申請短信簽名,擷取簽名通道号。
c. 已申請短信模闆,擷取模闆ID。
官方說明位址: https://support.huaweicloud.co
composer安裝Guzzle 可能會比較慢,耐心等待下
接下來就是封裝好短信發送類代碼如下:
<?php
namespace HWcloud;
require 'vendor/autoload.php';
use GuzzleHttp\Psr7;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class HuaWeiCloud
{
private $appkey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
private $appSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
private $sender = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //國内短信簽名通道号或國際/港澳台短信通道号
private $templateId = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
private $statusCallback = '';//選填,短信狀态報告接收位址,推薦使用域名,為空或者不填表示不接收狀态報告
private $url = 'https://api.rtc.huaweicloud.com:10443/sms/batchSendSms/v1';//請求位址接口
/**
* 發送短信驗證碼
* @param string $phone 手機号碼
* @param string $code 短信驗證碼
* @param string $signature 簽名名稱國際/港澳台短信不用關注該參數
* @return string
*/
public function sendMsgCode($phone,$code,$signature){
$templateParas = "[\"".$code."\"]"; //模闆變量
$client = new Client();
try{
$response = $client->request('POST', $this->url,[
'form_params' => [
'from' => $this->sender,
'to' => $phone,
'templateId' => $this->templateId,
'templateParas' => $templateParas,
'statusCallback' => $this->statusCallback,
'signature' => $signature //使用國内短信通用模闆時,必須填寫簽名名稱
],
'headers' => [
'Authorization' => 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
'X-WSSE' => $this->buildWsseHeader($this->appkey,$this->appSecret)
],
'verify' => false //為防止因HTTPS證書認證失敗造成API調用失敗,需要先忽略證書信任問題
]);
//echo Psr7\str($response); //列印響應資訊
//echo $response -> getStatusCode(); //擷取發送狀态
//echo $response ->getBody();//擷取發送主題内容
return json_decode($response ->getBody(),true);
}catch(RequestException $e) {
echo Psr7\str($e->getRequest()), "\n";
if($e->hasResponse()){
echo Psr7\str($e->getResponse());
}
}
}
/**
* 構造X-WSSE參數值
* @param string $appKey
* @param string $appSecret
* @return string
*/
private function buildWsseHeader(){
$now = date('Y-m-d\TH:i:s\Z'); //Created
$nonce = uniqid(); //Nonce
$base64 = base64_encode(hash('sha256', ($nonce . $now . $this->appSecret))); //PasswordDigest
return sprintf("UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"",$this->appkey, $base64, $nonce, $now);
}
}
執行個體化目前類,調用sendMsgCode方法即可(填寫對應的參數)