主题
:
laravel
、api、thirdpartyintegration、web 开发 php laraveltips apisinlaravel
将第三方 api 集成到 laravel 中可以通过利用外部服务(例如支付、数据检索等)来增强您的应用程序。以下是有效集成第三方 api 的分步指南和示例。
先决条件:
一个可以运行的 laravel 安装。
第三方 api(我们将使用天气 api 作为示例)。
第 1 步:
设置您的 api 密钥和环境变量
首先,注册第三方api并获取您的api密钥。在 laravel 的 .env 文件中存储 api 密钥等敏感信息。
获取 api 密钥
:注册第三方 api(例如 openweathermap)并检索您的 api 密钥。
添加到.env
:
步骤 2:
安装 guzzle(http 客户端)
laravel 使用 guzzle(一个 php http 客户端)来发出 http 请求。如果您的 laravel 项目中尚未安装 guzzle,请安装它:
步骤 3:
为 api 请求创建服务类
为了保持代码井井有条,请创建一个服务类来处理 api 集成逻辑。
创建一个新的服务类
:
运行以下命令来创建服务类:
实现服务类
:
在 app/services/weatherservice.php 中,编写一个函数来从天气 api 中获取数据。
步骤4:
将服务绑定到服务提供者
要使 weatherservice 在您的应用程序中可访问,请将其绑定到服务提供者中。
创建新的服务提供商
:
在 apiserviceprovider.php 中注册服务
:
在 app/providers/apiserviceprovider.php 中,添加:
注册服务提供商
:
在config/app.php中,将appprovidersapiserviceprovider::class添加到providers数组中。
第5步:
创建api交互的控制器
要处理 api 请求和响应,请创建一个控制器来与 weatherservice 交互。
Git
程序猿必备版本控制工具
下载
生成控制器
:
使用控制器中的服务
:
在 app/http/controllers/weathercontroller.php 中,添加:
第 6 步:
定义路线
添加路由以根据城市名称发出 api 请求。
更新routes/web.php
:
第7步:
创建一个视图来显示天气数据
创建一个视图来显示从 api 获取的天气信息。
创建视图
:
在 resources/views/weather/show.blade.php 中,添加:
第 8 步:
测试集成
启动 laravel 开发服务器:
访问 http://localhost:8000/weather/{city},将 {city} 替换为您要检查的城市名称(例如伦敦)。
概括
您现在已经按照以下步骤将第三方 api 集成到 laravel 应用程序中:
在环境文件中设置 api 密钥。
安装并配置 http 客户端。
创建一个服务来处理 api 请求。
将服务绑定到服务提供者中。
创建一个控制器来使用该服务。
定义路线。
构建一个视图来显示数据。
测试您的集成。
此设置遵循 laravel 最佳实践,使您的代码保持模块化和安全。这种方法可以扩展到您想要集成的任何第三方 api!
与我联系:@ linkedin 并查看我的作品集。
请给我的
git
hub 项目一颗星 ⭐️
weather_api_key=your_api_key_here
weather_api_url=https://api.openweathermap.org/data/2.5/weather
composer require guzzlehttp/guzzle
php artisan make:service weatherservice
client = $client;
}
public function getweather($city)
{
$url = env('weather_api_url');
$apikey = env('weather_api_key');
$response = $this->client->get($url, [
'query' => [
'q' => $city,
'appid' => $apikey,
'units' => 'metric' // or 'imperial' for fahrenheit
]
]);
return json_decode($response->getbody(), true);
}
}
php artisan make:provider apiserviceprovider
app->singleton(weatherservice::class, function () {
return new weatherservice(new client());
});
}
public function boot()
{
//
}
}
php artisan make:controller weathercontroller
weatherservice = $weatherservice;
}
public function show($city)
{
$weatherdata = $this->weatherservice->getweather($city);
return view('weather.show', ['weather' => $weatherdata]);
}
}
use app\http\controllers\weathercontroller;
route::get('/weather/{city}', [weathercontroller::class, 'show']);
weather information
weather in {{ $weather['name'] }}
temperature: {{ $weather['main']['temp'] }}°c
condition: {{ $weather['weather'][0]['description'] }}
humidity: {{ $weather['main']['humidity'] }}%
php artisan serve
