
本文介绍了如何在 Laravel 控制器中使用 AJAX GET 请求获取的数据来更新数据库,而无需在成功后进行额外的 AJAX 请求。重点在于理解如何正确处理 Paystack 支付验证后的数据,并将其安全地更新到用户表中。同时,也强调了 CSRF 令牌的重要性以及正确的数据赋值方式。
首先,我们需要一个支付表单,并使用 Paystack 的 JavaScript 库来处理支付流程。以下是一个示例:
<form id="paymentForm">
<div class="form-group">
<label for="email">Email Address</label> <br>
<input type="email" id="email-address" required />
</div>
<div class="form-group">
<label for="amount">Amount</label><br>
<input type="tel" id="amount" required />
</div>
<div class="form-submit">
<button type="submit" onclick="payWithPaystack(event)"> Pay </button>
</div>
</form>
<script src="https://js.paystack.co/v1/inline.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
const paymentForm = document.getElementById('paymentForm');
paymentForm.addEventListener("submit", payWithPaystack, false);
function payWithPaystack(e) {
e.preventDefault();
let handler = PaystackPop.setup({
key: 'pk_test_YOUR_PUBLIC_KEY', // 替换为你的 Paystack 公钥
email: document.getElementById("email-address").value,
amount: document.getElementById("amount").value * 100,
ref: ''+Math.floor((Math.random() * 1000000000) + 1), // 生成一个伪唯一的引用。建议替换为服务端生成的引用。
onClose: function(){
alert('Window closed.');
},
callback: function(response){
let reference = response.reference;
// 验证支付
$.ajax({
type: "GET",
url: "{{URL::to('verify-payment')}}/"+reference,
success: function(response){
console.log(response);
}
});
}
});
handler.openIframe();
}
</script>注意事项:
在 routes/web.php 中定义 AJAX GET 路由:
Route::get('verify-payment/{reference}', 'UsersController@verify_pay')->name('verify-payment');在 UsersController.php 中,实现 verify_pay 方法:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class UsersController extends Controller
{
public function verify_pay($reference)
{
$sec = "sk_test_YOUR_SECRET_KEY"; // 替换为你的 Paystack 密钥
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $sec,
'Cache-Control' => 'no-cache',
])->get("https://api.paystack.co/transaction/verify/$reference");
$newData = $response->json();
if ($newData['status'] == true) {
$amount = $newData['data']['amount'] / 100;
$user = Auth::user();
$user->donation_sum = $amount; // 直接赋值
$user->save();
return "paid";
} else {
return "something went wrong";
}
}
}关键点:
总结:
通过以上步骤,你可以在 Laravel 控制器中使用 AJAX GET 请求获取的数据来更新数据库,而无需额外的 AJAX 请求。 关键在于正确验证 Paystack 支付,并安全地更新用户数据。 确保使用 Laravel HTTP Client 发起请求,并注意数据赋值和 CSRF 保护。 同时,需要考虑更完善的错误处理机制,以确保应用程序的稳定性和用户体验。
以上就是Laravel 中使用 AJAX GET 请求更新数据库的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号