使用Laravel将消息和文件发送到WhatsApp是一个常见的需求,可以通过以下步骤实现:
composer create-project --prefer-dist laravel/laravel whatsapp-sender
。composer require twilio/sdk
。.env
文件中,添加以下Twilio凭证信息:TWILIO_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_WHATSAPP_NUMBER=your_twilio_whatsapp_number
确保将your_twilio_account_sid
、your_twilio_auth_token
和your_twilio_whatsapp_number
替换为你的Twilio账号相关信息。
routes/web.php
文件中添加以下路由:Route::post('/send-message', 'WhatsAppController@sendMessage');
然后,在app/Http/Controllers/WhatsAppController.php
文件中创建sendMessage
方法,用于发送消息:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twilio\Rest\Client;
class WhatsAppController extends Controller
{
public function sendMessage(Request $request)
{
$message = $request->input('message');
$to = $request->input('to');
$twilioSid = config('app.twilio_sid');
$twilioToken = config('app.twilio_auth_token');
$twilioNumber = config('app.twilio_whatsapp_number');
$twilio = new Client($twilioSid, $twilioToken);
$twilio->messages->create(
"whatsapp:$to",
[
'from' => "whatsapp:$twilioNumber",
'body' => $message
]
);
return response()->json(['message' => 'Message sent successfully']);
}
}
resources/views/welcome.blade.php
文件中添加以下代码:<!DOCTYPE html>
<html>
<head>
<title>WhatsApp Sender</title>
</head>
<body>
<h1>WhatsApp Sender</h1>
<form action="/send-message" method="POST">
@csrf
<label for="to">To:</label>
<input type="text" name="to" id="to" required><br><br>
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea><br><br>
<button type="submit">Send</button>
</form>
</body>
</html>
php artisan serve
。然后在浏览器中访问http://localhost:8000
,即可看到WhatsApp发送界面。这样,使用Laravel将消息和文件发送到WhatsApp的功能就实现了。请注意,上述代码仅为示例,实际应用中可能需要进行更多的错误处理和安全性措施。
领取专属 10元无门槛券
手把手带您无忧上云