简体   繁体   English

Yii2 - 在外部 URL 上执行 http 表单 POST 并重定向到它

[英]Yii2 - Do a http form POST on external URL and redirect to it

I have an application on Yii2.我在 Yii2 上有一个应用程序。

I have an external vendor i want to redirect.我有一个要重定向的外部供应商。 For example, i am encrypting the current user info, and want to send that to the external vendor, so the user information is automatically populated on his website.例如,我正在加密当前用户信息,并希望将其发送给外部供应商,因此用户信息会自动填充到他的网站上。

Everything works fine if i do that on the front end side using JS.如果我在前端使用 JS 执行此操作,一切正常。

The problem i have is only my app server is whitelisted to the vendor.我的问题是只有我的应用服务器被列入供应商的白名单。 So i need to make the redirection happen on the backend.所以我需要在后端进行重定向。

I tried several method, and even with Guzzle HTTP, and it doesn't redirect.我尝试了几种方法,即使使用 Guzzle HTTP,它也不会重定向。

TO be clear, i am not looking for a simple redirect, it is a form post on external URL.需要明确的是,我不是在寻找简单的重定向,它是外部 URL 上的表单发布。

I went though this post, but the problem remain the same... Yii2 how to send form request to external url我去了这篇文章,但问题还是一样... Yii2 如何将表单请求发送到外部 url

Does anybody faced this issue?有人遇到过这个问题吗?

If I understand you correctly, you want to POST data received from your frontend to the server of a third party company (let's call them ACME).如果我理解正确,您想将从前端收到的数据 POST 到第三方公司的服务器(我们称之为 ACME)。 Your webserver is whitelisted by ACME but your clients are not (which is good).您的网络服务器已被 ACME 列入白名单,但您的客户端没有(这很好)。 You want to show a page on your server and not a page on the ACME server after the POST, right?您想在 POST 之后在您的服务器上显示一个页面,而不是在 ACME 服务器上显示一个页面,对吗?

You have to send the data with a separate request from your server to the ACME server.您必须通过单独的请求将数据从您的服务器发送到 ACME 服务器。 You cannot create a HTML <form> and put the ACME server in the action parameter of it, because the request would be sent from the client and not your backend, failing at the whitelist.你不能创建一个 HTML <form>并将 ACME 服务器放在它的action参数中,因为请求将从客户端而不是你的后端发送,在白名单中失败。 After you validate your client input, you can send it with guzzle to ACME.在您验证您的客户端输入后,您可以将其连同 guzzle 发送到 ACME。

With the status code you can decide if your request was successful or not.通过状态代码,您可以决定您的请求是否成功。 You can read more about guzzle here您可以在此处阅读有关 guzzle 的更多信息

The code sample below shows how you could POST the $payload (a fictional blog post if you will) as JSON to the ACME server and output a line with the request result.下面的代码示例显示了如何将$payload (如果您愿意,可以写一篇虚构的博客文章)作为 JSON 发布到 ACME 服务器并输出一行包含请求结果的内容。

$payload = [
    'username' => 'john.doe',
    'postContent' => 'Hello world',
];

$client = new GuzzleHttp\Client();
$response = $client->post('https://acme.example.org/endpoint',['http_errors' => false, 'json' => $payload]);

if($response->getStatusCode() === 200){
    echo "Request OK";
}else{
    echo "Request failed with status ".$response->getStatusCode();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM