php larvael实现发送短信腾讯云

1、首先,需要在腾讯云控制台开通短信服务,并创建应用和签名模板。

2、然后,在 Laravel 项目中安装并配置 GuzzleHTTP 客户端库。可以使用 Composer 命令安装:

composer require guzzlehttp/guzzle:^7.0

3、 在 Laravel 项目中创建一个发送短信的服务,例如在 app/Services 目录下创建 SmsService.php 文件,其中编写发送短信的方法:

<?php

namespace App\Services;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class SmsService
{
    public function sendSms($mobile, $templateId, $params)
    {
        $client = new Client();
        $url = 'https://sms.tencentcloudapi.com/';
        $timestamp = time();
        $nonce = rand(100000, 999999);

        // 根据腾讯云API文档,构建所需的请求参数
        $requestParams = [
            'Action' => 'SendSms',
            'Version' => '2019-07-11',
            'Region' => 'ap-guangzhou',
            'Timestamp' => $timestamp,
            'Nonce' => $nonce,
            'PhoneNumberSet.0' => '+86' . $mobile,
            'TemplateID' => $templateId,
            'TemplateParamSet' => $params
        ];

        // 根据腾讯云API文档,生成签名
        ksort($requestParams);
        $signatureStr = '';
        foreach ($requestParams as $key => $value) {
            $signatureStr .= $key . '=' . urlencode(strval($value)) . '&';
        }
        $secretKey = 'your-secret-key'; // 从腾讯云控制台获取
        $signatureStr .= 'SecretId=your-secret-id'; // 从腾讯云控制台获取
        $signature = urlencode(base64_encode(hash_hmac("sha1", $signatureStr, $secretKey, true)));

        // 发送HTTP请求,并得到响应结果
        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'form_params' => [
                'Signature' => $signature,
            ] + $requestParams,
        ]);

        // 解析响应结果
        $resultData = json_decode($response->getBody()->getContents(), true);

        Log::info('Send SMS result:', $resultData);

        return $resultData;
    }
}

4、在需要发送短信的地方使用 SmsService 类的 sendSms 方法即可。例如,在控制器中:

<?php

namespace App\Http\Controllers;

use App\Services\SmsService;

class SomeController extends Controller
{
    public function sendSms(SmsService $smsService)
    {
        $mobile = 'xxxxxxxxxxx';
        $templateId = 'xxxxxxxxx';
        $params = ['param1' => 'value1', 'param2' => 'value2'];
        $result = $smsService->sendSms($mobile, $templateId, $params);
        return $result;
    }
}

 其中,$mobile 表示手机号码,$templateId 表示短信模板 ID,$params 表示短信模板的参数。需要根据实际情况进行修改。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值