首页 > 解决方案 > Symfony - 在控制器中使用发布数据重定向

问题描述

目标是在我的网站上注册一个空闲用户,并通过 POST 方法发送在表单中输入的用户数据,将其重定向到支付平台。

如果此表单有效,我在 POST 中有一个表单,用于创建非活动用户。然后,我想将我的用户重定向到一个外部 URL,同时将数据从这个表单以 POST 发送到这个 URL。这个 URL 只接受特定的变量名(这些变量在我的 RedirectResponse 的关联数组中)并且只接受 POST。

用户将在外部链接上付款,如果付款成功,我将稍后激活用户。我通过发送她的“ID”来识别支付平台,她已经授权了我的域名。

我尝试使用状态为 307 的 RedirectResponse,但我认为无法发送 POST 数据。

     * @Route("/{id<\d+>?1}/{slug}", methods={"GET", "POST"}, name="show")
     * @Security("is_granted('IS_AUTHENTICATED_ANONYMOUSLY')")
     */
    public function show(Offre $offre, $slug, Request $request): Response
    {
        if ($offre->getSlug() !== $slug) {
            return $this->redirectToRoute('site_devenir_vip_show', [
                'id'   => $offre->getId(),
                'slug' => $offre->getSlug(),
            ], Response::HTTP_MOVED_PERMANENTLY);
        }

        $utilisateur = new User();

        $form = $this->createForm(UserType::class, $utilisateur);
        $form->handleRequest($request);

        if ($form->isSubmitted() === true) {
            if ($form->isValid() === true) {
                // TODO: create the inactive User here

                // TODO: redirect the user on the payment platform
                return new RedirectResponse('https://mywebsite.com', 307, [
                    'NOM'        => $utilisateur->getNom(),
                    'PRENOM'     => $utilisateur->getPrenom(),
                    'TEL'        => $utilisateur->getTel(),
                    'EMAIL'      => $utilisateur->getEmail(),
                    'PAYS'       => $utilisateur->getPays(),
                    'ID'         => 'XXXX',
                    'ABONNEMENT' => 'XXXX',
                ]);
            }

            $this->addFlash('error', 'Le formulaire comporte des erreurs.');
        }

        return $this->render('site/pages/devenir_vip/show.html.twig', [
            'offre' => $offre,
            'form'  => $form->createView(),
        ]);
    }

我目前被重定向到 RedirectResponse 中的外部链接,但它没有获取参数。你有想法吗 ?

标签: phpsymfonyhttp

解决方案


POST请求方法,而不是响应“方法”。请求具有方法(GETPOSTPUTPATCHHEAD等),响应具有状态码(200404500等)。

您可能需要通过使用来自 php 的 HTTP 客户端将数据发送到 Gate 来创建付款,然后重定向用户(如果付款已创建)。支付门通常会响应您应该将用户重定向到的网址。请参阅您的门的 API 文档。

Symfony 默认不包含 HTTP 客户端(反正不是一个合适的客户端)。我推荐Guzzle

模拟代码:

if ($form->isSubmitted() === true) {
    if ($form->isValid() === true) {
        $httpClient = new Client();

        $response = $httpClient->post('https://paymentgate.com', [
            'key' => 'value',
        ]);

        // Validate response somehow
        if ($response->statusCode() !== 200) {
            $this->addFlash('error', 'Payment gate failed to respond');
        } else {
            // Let's assume that the gate returns a json with key 'redirect' containing the url
            $json = json_decode($response->getContent());
            return new RedirectResponse($json->redirect);
        }
    }

    $this->addFlash('error', 'Le formulaire comporte des erreurs.');
}

推荐阅读