Laravel使用Facade集成Nexmo:如何获取发送状态及账户余额?
Hey there! Let's walk through how to get your Nexmo (now Vonage) integration in Laravel sorted with exactly the features you need: tracking SMS delivery status (including failure details) and checking your account balance. I'll start by fixing the syntax in your code snippet and then break down each feature step by step.
First up, your existing code has a small syntax error—you need to use the send() method and pass an array of parameters. Here's the corrected base code with error handling:
use Nexmo\Client\Exception\ClientException; try { $response = Nexmo::message()->send([ 'to' => '+1234567890', // Use E.164 format (country code + number) 'from' => 'YOUR_NEXMO_NUMBER', // Your verified Nexmo/Vonage number 'text' => 'Test message from Laravel!' ]); // Handle successful initial response $messageId = $response['messages'][0]['message-id']; $initialStatus = $response['messages'][0]['status']; // Store this in your database for tracking (example) // SMSLog::create(['message_id' => $messageId, 'status' => $initialStatus]); echo "Message queued! ID: {$messageId}, Initial Status: {$initialStatus}"; } catch (ClientException $e) { // Catch immediate errors (e.g., invalid number, insufficient balance) $errorData = json_decode($e->getResponse()->getBody()->getContents(), true); $errorCode = $errorData['messages'][0]['error-code']; $errorMessage = $errorData['messages'][0]['error-text']; echo "Failed to send message! Error Code: {$errorCode}, Details: {$errorMessage}"; }
What the initial status means:
0: Nexmo has accepted the message for delivery- Non-zero values: Immediate failure (e.g.,
1= invalid destination,3= insufficient balance)
The initial status only tells you if Nexmo accepted the message. To get the actual delivery status (e.g., delivered, failed, pending), you need to set up a webhook (callback URL) that Nexmo will hit when the message status changes.
Step 1: Configure Webhook in Nexmo Dashboard
- Log into your Nexmo/Vonage dashboard
- Go to "Settings" > "API Settings"
- Under "Delivery Receipts", enter your public URL (e.g.,
https://yourdomain.com/nexmo/delivery-webhook) - Set the request method to
POST
Step 2: Handle the Webhook in Laravel
First, add a route in routes/web.php:
use App\Http\Controllers\NexmoController; Route::post('/nexmo/delivery-webhook', [NexmoController::class, 'handleDeliveryStatus']);
Then create the controller method to process the webhook data:
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class NexmoController extends Controller { public function handleDeliveryStatus(Request $request) { // Extract data from Nexmo's webhook payload $messageId = $request->input('messageId'); $deliveryStatus = $request->input('status'); $errorCode = $request->input('err-code'); $errorDescription = $request->input('err-code-desc'); // Update your SMS log with the latest status DB::table('sms_logs')->updateOrInsert( ['message_id' => $messageId], [ 'status' => $deliveryStatus, 'error_code' => $errorCode, 'error_description' => $errorDescription, 'updated_at' => now() ] ); // Return a 200 OK to acknowledge the webhook (Nexmo will retry if it gets an error) return response()->json(['status' => 'received'], 200); } }
Common Delivery Status Values:
delivered: Message successfully received by the recipientfailed: Message couldn't be delivered (checkerr-codefor specific details)pending: Message is still in transitrejected: Nexmo rejected the message (e.g., flagged as spam)
Getting your remaining balance is straightforward with the Nexmo Facade's account()->balance() method. Here's how to implement it:
use Nexmo\Client\Exception\ClientException; try { $balanceData = Nexmo::account()->balance(); $remainingBalance = $balanceData['value']; $currency = $balanceData['currency']; echo "Current Nexmo Balance: {$remainingBalance} {$currency}"; } catch (ClientException $e) { $error = json_decode($e->getResponse()->getBody()->getContents(), true); echo "Failed to fetch balance: {$error['error-text']}"; }
- E.164 Format: Always use the international number format (e.g.,
+1234567890) for bothtoandfromfields—this avoids routing errors. - Local Development: If you're testing locally, use a tool like ngrok to expose your webhook URL publicly (Nexmo can't reach localhost).
- Environment Variables: Make sure your
.envfile has validNEXMO_KEYandNEXMO_SECRETvalues (you can get these from your Nexmo dashboard). - Error Logging: Instead of echoing errors, log them to Laravel's log system (using
Log::error()) for better debugging.
内容的提问来源于stack exchange,提问作者hsn_ch

