Laravel 接入 腾讯短信

164 阅读2分钟

要在 Laravel 中接入腾讯云短信服务,可以通过以下步骤实现:

步骤 1:安装腾讯云短信 SDK

你可以通过 Composer 安装腾讯云短信 SDK:

composer require tencentcloud/tencentcloud-sdk-php

步骤 2:配置腾讯云短信服务的 API 密钥

从腾讯云的 短信控制台 获取你的 API 密钥(SecretIdSecretKey)以及短信应用的 AppId

然后,你可以将这些密钥添加到 .env 文件中,方便在项目中调用:

TENCENT_SMS_SECRET_ID=your-secret-id
TENCENT_SMS_SECRET_KEY=your-secret-key
TENCENT_SMS_APP_ID=your-app-id
TENCENT_SMS_SIGN=your-sign-name  # 短信签名

步骤 3:在服务中调用腾讯云短信 API

在 Laravel 中,可以创建一个服务类来处理短信的发送逻辑。以下是一个简单的服务类示例:

1. 创建短信服务类

<?php

namespace App\\Services;

use TencentCloud\\Common\\Credential;
use TencentCloud\\Common\\Exception\\TencentCloudSDKException;
use TencentCloud\\Sms\\V20210111\\SmsClient;
use TencentCloud\\Sms\\V20210111\\Models\\SendSmsRequest;

class TencentSmsService
{
    protected $secretId;
    protected $secretKey;
    protected $appId;
    protected $sign;

    public function __construct()
    {
        $this->secretId = env('TENCENT_SMS_SECRET_ID');
        $this->secretKey = env('TENCENT_SMS_SECRET_KEY');
        $this->appId = env('TENCENT_SMS_APP_ID');
        $this->sign = env('TENCENT_SMS_SIGN');
    }

    /**
     * 发送短信
     *
     * @param string $phoneNumber 接收短信的手机号码
     * @param string $templateId 短信模板 ID
     * @param array $templateParams 模板参数
     * @return bool
     */
    public function sendSms($phoneNumber, $templateId, $templateParams)
    {
        try {
            // 创建认证信息
            $cred = new Credential($this->secretId, $this->secretKey);

            // 创建短信客户端
            $client = new SmsClient($cred, "ap-guangzhou");

            // 构造请求
            $req = new SendSmsRequest();

            // 配置应用 ID 和签名
            $req->SmsSdkAppId = $this->appId;
            $req->SignName = $this->sign;
            $req->TemplateId = $templateId;

            // 设置发送的手机号码,格式为["+86<手机号码>"]
            $req->PhoneNumberSet = ["+86" . $phoneNumber];

            // 设置模板参数
            $req->TemplateParamSet = $templateParams;

            // 发送请求
            $resp = $client->SendSms($req);

            // 处理响应结果
            if ($resp->SendStatusSet[0]->Code === "Ok") {
                return true;
            }

            return false;
        } catch (TencentCloudSDKException $e) {
            return false;
        }
    }
}

2. 调用短信服务类

你可以在控制器或其他逻辑中使用这个服务类来发送短信:

use App\\Services\\TencentSmsService;

public function sendVerificationCode(Request $request)
{
    $phoneNumber = $request->input('phone');
    $code = rand(1000, 9999);  // 生成 4 位验证码
    $templateId = 'your-template-id'; // 替换为你的模板 ID

    // 创建腾讯云短信服务实例
    $smsService = new TencentSmsService();

    // 发送短信
    $isSent = $smsService->sendSms($phoneNumber, $templateId, [$code]);

    if ($isSent) {
        return response()->json(['message' => '短信发送成功', 'code' => $code], 200);
    } else {
        return response()->json(['message' => '短信发送失败'], 500);
    }
}

步骤 4:配置短信模板

在腾讯云短信服务控制台,配置好你的短信模板,记录模板 ID,替换到代码中的 $templateId 中。模板内容中会有类似 {1} 的占位符,$templateParams 数组会按照顺序填充这些占位符。

总结

通过 Composer 安装腾讯云 SDK,配置 .env 文件中的密钥,创建一个服务类处理短信发送逻辑,你就可以在 Laravel 项目中轻松接入腾讯云短信服务。

你需要在腾讯云短信控制台中配置好签名和模板,并且确保你的腾讯云短信服务已经开通。