-1

Symfony 5.3.10

PHP 8.0.8

我有一个用于用户激活的公共 webhook(通过单击电子邮件中的链接)。

就像是:https://mydomain.fake/user/123-5346-6787-89-789/1234678567945asd

激活是通过 api 请求执行的,所以我需要在 webhook 的控制器内生成一个子请求

#[Route('/activate/{uuid}/{token}', name: 'webhook.user_settings')]
    public function index(string $uuid, string $token, Request $request, HttpKernelInterface $httpKernel): Response
    {

        $url = sprintf($request->getSchemeAndHttpHost() . "/api/user/%s/activate?token=%s",
            $uuid,
            $token
        );

        $request = Request::create($url, 'PATCH', [], [], [], [], json_encode([], \JSON_THROW_ON_ERROR));
        $request->setMethod('PATCH');
        $request->headers->set('Content-Type', 'application/merge-patch+json');

        $result = $httpKernel->handle($request, HttpKernelInterface::SUB_REQUEST);

        if ($result->getStatusCode() === Response::HTTP_OK) {
            $user = json_decode($result->getContent());
            $body = "<html><body><h2>Complimenti '" . $user->name . "', attivazione avvenuta con successo</h2></body></html>";
        } else {
            $body = "<html><body><h2>Ooops! Qualcosa è andato storto</h2></body></html>";
        }
        return new Response($body, $result->getStatusCode());
    }

它一直工作到今天(我在一周前的最后一次测试,但它工作了好几个月)

现在执行对 api 的请求,用户激活$result处于状态 400

Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\BadRequestHttpException: "There is currently no session available."

如果我直接调用 api(使用 Postman),它会按预期工作。

我哪里错了?

4

1 回答 1

0

通过将主请求的会话添加到子请求中解决

public function index(string $uuid, string $token, Request $request, HttpKernelInterface $httpKernel): Response
    {

        $url = sprintf($request->getSchemeAndHttpHost() . "/api/user/%s/activate?token=%s",
            $uuid,
            $token
        );
        $session = $request->getSession();
        $request = Request::create($url, 'PATCH', [], [], [], [], json_encode([], \JSON_THROW_ON_ERROR));
        $request->setMethod('PATCH');
        $request->headers->set('Content-Type', 'application/merge-patch+json');
        $request->setSession($session);

        $result = $httpKernel->handle($request, HttpKernelInterface::SUB_REQUEST);

        if ($result->getStatusCode() === Response::HTTP_OK) {
            $user = json_decode($result->getContent());
            $body = "<html><body><h2>Complimenti '" . $user->name . "', attivazione avvenuta con successo</h2></body></html>";
        } else {
            $body = "<html><body><h2>Ooops! Qualcosa è andato storto</h2></body></html>";
        }
        return new Response($body, $result->getStatusCode());
    }
于 2021-11-04T14:59:04.887 回答