Flutter中如何实现HTTP POST请求跳转至PayFast支付页面?
问题描述
我正在使用本地支付网关API PayFast。以下是运行正常的HTML沙箱实现:
<form action="https://sandbox.payfast.co.za/eng/process" method="post"> <input type="hidden" name="merchant_id" value="10000100"> <input type="hidden" name="merchant_key" value="46f0cd694581a"> <input type="hidden" name="amount" value="100.00"> <input type="hidden" name="item_name" value="Test Product"> <input type="submit"> </form>
我尝试通过Flutter的Dio库实现相同效果,目前编写的代码如下:
var formData = FormData.fromMap({ 'merchant_key': '46f0cd694581a', 'merchant_id': '10000100', 'amount': '123.45', 'item_name': '#BP000123', }); var response = await Dio().post( "https://sandbox.payfast.co.za/eng/process", data: formData, );
问题在于请求响应并未跳转至支付页面,请问该如何实现这一跳转功能?
解决方案
Dio发起的是后台HTTP请求,它只会获取接口返回的内容,不会像浏览器那样自动处理页面跳转逻辑(比如解析HTML跳转、处理重定向响应)。PayFast的/eng/process接口返回的是支付页面HTML或重定向指令,但Dio不会渲染这些内容,自然无法触发跳转。
要实现跳转,你需要用Flutter的WebView组件模拟浏览器的表单提交行为,具体步骤如下:
- 添加WebView依赖(如
webview_flutter)到pubspec.yaml。 - 构造包含PayFast表单的HTML字符串,设置自动提交逻辑。
- 在WebView中加载这段HTML,自动触发表单提交即可跳转到支付页面。
示例代码:
import 'package:webview_flutter/webview_flutter.dart'; // 构造自动提交的HTML表单 String buildPayFastForm() { return ''' <html> <body onload="document.getElementById('payfast-form').submit()"> <form id="payfast-form" action="https://sandbox.payfast.co.za/eng/process" method="post"> <input type="hidden" name="merchant_id" value="10000100"> <input type="hidden" name="merchant_key" value="46f0cd694581a"> <input type="hidden" name="amount" value="123.45"> <input type="hidden" name="item_name" value="#BP000123"> </form> </body> </html> '''; } // 在页面中使用WebView加载这段HTML WebView( initialUrl: Uri.dataFromString( buildPayFastForm(), mimeType: 'text/html', ).toString(), javascriptMode: JavascriptMode.unrestricted, // 必须启用JS才能自动提交表单 )
你也可以直接在WebView加载空白页面后,通过evaluateJavascript动态创建并提交表单,效果一致。
注意:确保WebView配置了网络权限,同时要监听支付完成后的URL变化,当跳转到你的回调页面时,关闭WebView并处理后续业务逻辑。
内容的提问来源于stack exchange,提问作者Brandon Pillay
相关产品推荐
相关产品推荐

