You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

1. Fixing the Basic SMS Sending Code

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)
2. Tracking Full Delivery Status (Including Failures)

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

  1. Log into your Nexmo/Vonage dashboard
  2. Go to "Settings" > "API Settings"
  3. Under "Delivery Receipts", enter your public URL (e.g., https://yourdomain.com/nexmo/delivery-webhook)
  4. 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 recipient
  • failed: Message couldn't be delivered (check err-code for specific details)
  • pending: Message is still in transit
  • rejected: Nexmo rejected the message (e.g., flagged as spam)
3. Checking Your Nexmo Account Balance

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']}";
}
4. Quick Tips to Avoid Headaches
  • E.164 Format: Always use the international number format (e.g., +1234567890) for both to and from fields—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 .env file has valid NEXMO_KEY and NEXMO_SECRET values (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:05:32