概述
uniapp 和很多小程序都会用到云函数。这里以 dcloud 的 unipush 云函数为例,记录 Laravel 侧如何发起 HTTP 请求。
这也可以作为传统服务器接入 unipush 2.0 的参考。unipush 2.0 取消了传统服务器的身份验证,可以通过云函数 URL 化来处理。
实践
使用 GuzzleHttp\Client 构建请求
先安装 Guzzle HTTP 客户端:
composer require guzzlehttp/guzzle
然后在控制器中构建请求:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class YourController extends Controller
{
public function test_unipush()
{
$data = [
"cids" => ['15f2d1111de1ef5aa3f8911dab53ffb2'], // 设备id,注意这里使用数组形式
"title" => 'Test', // 标题
"content" => '123', // 内容
"payload" => '', // 数据
"force_notification" => 'true', // 自动创建“通知栏消息”
"request_id" => '12345678982', // 请求唯一标识号
];
// 确保数据被正确编码为 JSON
$jsonData = json_encode($data);
// 输出 JSON 编码后的数据,以便验证
var_dump($jsonData);
try {
$client = new Client();
$response = $client->request('POST', 'https://your-cloud-function-url.com/send-push-notification', [
'headers' => [
'Content-Type' => 'application/json',
],
'body' => $jsonData,
]);
return response()->json(json_decode((string) $response->getBody(), true));
} catch (RequestException $e) {
return response()->json([
'error' => 'An error occurred while sending the request.',
'message' => $e->getMessage(),
], 500);
}
}
}
注意事项
- 确保已经通过 Composer 安装 Guzzle。
- 请求体需要正确编码为 JSON。
- 使用 Guzzle 的异常处理捕获请求失败,避免接口直接中断。
如何测试
访问 /test_unipush 端点时,可以先用 var_dump() 检查 JSON 编码后的数据结构,确认请求体符合云函数要求。
示例输出类似:
string(135) "{"cids":["15f2d1111de1ef5aa3f8911dab53ffb2"],"title":"Test","content":"123","payload":"","force_notification":"true","request_id":"12345678982"}"