首頁 >後端開發 >php教程 >你好,拉拉維爾?通過短信與PHP溝通!

你好,拉拉維爾?通過短信與PHP溝通!

William Shakespeare
William Shakespeare原創
2025-02-09 11:21:14548瀏覽

這個Laravel Weather App,最初是為語音通話而設計的,現在支持SMS通信。 這種增強涉及添加路由,修改服務層並創建SMS控制器來處理傳入的文本消息。

Hello, Laravel? Communicating with PHP through SMS!

路由加法:

文件已更新為包含SMS路由組:>

routes/web.php

路由處理所有傳入的SMS消息,利用Twilio的帖子請求。
<code class="language-php">Route::group(['prefix' => 'sms', 'middleware' => 'twilio'], function () {
    Route::post('weather', 'SmsController@showWeather')->name('weather');
});</code>

/sms/weather服務層修改:

文件的

方法已修改以適應SMS:

app/Services/WeatherService.php關鍵更改是添加getWeather>參數。 如果為true,則縮短了預測以適合SMS字符限制。

>
<code class="language-php">public function getWeather($zip, $dayName, $forSms = false) {
    // ... (Existing code to retrieve weather data remains unchanged) ...

    $weather = $day->name;
    $weather .= ' the ' . $tsObj->format('jS') . ': ';

    $response = new Twiml();

    if ($forSms) {
        $remainingChars = 140 - strlen($weather);
        // ... (Condensed weather forecast for SMS, limited to 140 characters) ...
        $response->message($weather);
    } else {
        // ... (Existing code for voice responses remains unchanged) ...
    }

    return $response;
}</code>

> SMS控制器: $forSms

>中創建了一個新的>

此控制器的SmsController.php方法使用app/Http/Controllers>用適當的參數來解釋SMS消息和調用

<code class="language-php"><?php
namespace App\Http\Controllers;

use App\Services\WeatherService;
use Illuminate\Http\Request;
use Twilio\Twiml;

class SmsController extends Controller
{
    // ... (Constructor and dependencies remain the same) ...

    public function showWeather(Request $request)
    {
        $parts = $this->parseBody($request);

        switch ($parts['command']) {
            case 'zipcode':
                // ... (Handle zipcode input) ...
                break;
            case 'day':
                // ... (Handle day of week input) ...
                break;
            case 'credits':
                // ... (Handle credits request) ...
                break;
            default:
                // ... (Handle default/unknown input) ...
                break;
        }

        return $response;
    }

    private function parseBody($request)
    {
        // ... (Parses the SMS body to determine user intent) ...
    }
}</code>
識別郵政編碼,一周的天數和信用請求。

showWeather> twilio配置:parseBody getWeather parseBody>更新您的twilio電話號碼設置,將SMS Webhook指向您的應用程序的

端點(使用ngrok url)。

應用程序用法: /sms/weather

>將帶有郵政編碼的SMS發送到您的Twilio號碼以接收天氣預報。 隨後的消息可以指定一周中的一天或請求信用。

> Hello, Laravel? Communicating with PHP through SMS!

這種增強的Laravel應用程序展示了一種使用Twilio來處理語音和SMS交互的強大而靈活的方法。 該代碼提供了一個明確的示例,說明如何擴展功能以支持新的通信渠道。 請記住,用原始響應中的實際代碼替換佔位符評論。

>

以上是你好,拉拉維爾?通過短信與PHP溝通!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn