使用 Laravel 发起HTTP 请求到云函数

由 Jefsky 发布于 2024-08-18

概述

  1. uniapp和众多的小程序都用云函数,这里以 dcloud 的 unipush 云函数作为例子简述

  2. 也可以作为传统服务器针对 unipush2.0 应该怎么部署的例子

unipush 2.0 取消了传统服务器的身份验证,可直接通过云函数 url 化来处理

实践

使用 GuzzleHttp\Client 构建请求

  1. 安装 Guzzle:首先需要安装 Guzzle HTTP 客户端库,可以通过 Composer 安装:

    composer require guzzlehttp/guzzle

  2. 使用 Guzzle 发起请求:接下来,我们将使用 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);
        }
    }
}

注意事项

  1. Guzzle 安装:确保已经通过 Composer 安装了 Guzzle。

  2. 请求构造:使用 Guzzle 的 Client 类来构造请求,并确保请求体被正确设置。

  3. 错误处理:使用 Guzzle 提供的异常处理机制来捕获并处理异常。

如何测试

  1. 使用 var_dump(): 访问 /test_unipush 端点,您将在控制台看到 JSON 编码后的数据结构的输出。

  2. 检查请求:确认请求是否正确发送到目标 URL。

示例

当您访问 /test_unipush 端点时,您将看到类似以下的输出:

string(135) "{"cids":["15f2d1111de1ef5aa3f8911dab53ffb2"],"title":"Test","content":"123","payload":"","force_notification":"true","request_id":"12345678982"}"

著作权归作者所有。
商业转载请联系作者获得授权,非商业转载请注明出处。
作者:JefskyWong ——程序猿甜品店
链接:https://www.jefsky.com/blog/345
来源:https://www.jefsky.com/