#laravel #vuejs2 #axios #laravel-8 #mollie
Вопрос:
Я пытаюсь придумать подход, чтобы это сработало. Изначально у меня есть интегрированный поставщик платежных услуг, использующий Mollie. Существует множество функций, которые вызываются всякий раз, когда кто-то что-то покупает.
Именно здесь начинается оплата:
axios.post('/api/molliepayment', { products, totalPrice, paymentMethod, isSingleProduct }).then(response => {
window.open.location.href = response.data.data._links.checkout.href;
}).catch(() => {});
Способ, которым я использую Mollie, заключается в создании платежа в моем контроллере и возврате платежа в виде ответа json на представление Vue:
$payment = Mollie::api()->payments()->create([
'amount' => [
'currency' => 'EUR', // Type of currency you want to send
'value' => $totalPrice, // You must send the correct number of decimals, thus we enforce the use of strings
],
'method' => $method,
'description' => "Beschrijving",
'webhookUrl' => route('webhooks.mollie'),
'redirectUrl' => route('payment.success', ['is_singular' => $request->get('isSingleProduct') ? $request->get('isSingleProduct') : 0]),
"metadata" => [
"products" => $products,
"user_id" => Auth::id(),
"user" => Auth::user(),
"totalPrice" => $totalPrice,
],
]);
$payment = Mollie::api()->payments()->get($payment->id);
Теперь веб-крючок вызывается при открытии окна:
public function webhook(Request $request) {
if (! $request->has('id')) {
return;
}
$payment = Mollie::api()->payments()->get($request->id);
//Log::info('Test '.$payment->metadata->order_id);
$statusOfPayment='';
if ($payment->isPaid() amp;amp; !$payment->hasRefunds() amp;amp; !$payment->hasChargebacks()) {
/*
* The payment is paid and isn't refunded or charged back.
* At this point you'd probably want to start the process of delivering the product to the customer.
*/
$statusOfPayment='paid';
} elseif ($payment->isOpen()) {
/*
* The payment is open.
*/
$statusOfPayment='open';
} elseif ($payment->isPending()) {
/*
* The payment is pending.
*/
$statusOfPayment='pending';
} elseif ($payment->isFailed()) {
/*
* The payment has failed.
*/
$statusOfPayment='failed';
} elseif ($payment->isExpired()) {
/*
* The payment is expired.
*/
} elseif ($payment->isCanceled()) {
/*
* The payment has been canceled.
*/
$statusOfPayment='expired';
} elseif ($payment->hasRefunds()) {
/*
* The payment has been (partially) refunded.
* The status of the payment is still "paid"
*/
$statusOfPayment='partially refunded';
} elseif ($payment->hasChargebacks()) {
/*
* The payment has been (partially) charged back.
* The status of the payment is still "paid"
*/
$statusOfPayment='partially charged back';
}
$order = Order::create([
'user_id' => $payment->metadata->user_id,
'address_id' => 1,
'order_status' => $statusOfPayment,
'total_price' => $payment->metadata->totalPrice,
'is_delivered' => 0,
]);
// Log::info($payment->metadata->products);
// $order_details = $order->order_details()->create([
// 'quantity' => '1',
// 'totalPrice' => '8000',
// ]);
foreach($payment->metadata->products as $product) {
// Log::info($product->id);
$order_details = $order->order_details()->create([
'product_id' => $product->id,
'quantity' => $product->quantity,
'total_price' => $product->price * $product->quantity,
]);
$productUnits = Product::find($product->id);
$productUnits->decrement('units', $product->quantity);
$productUnits->save();
}
Mail::to($payment->metadata->user->email)->send(new OrderCreatedMail($order));
}
As last, when the payment succeeds, this function gets called:
public function paymentSuccess(Request $request, $id) {
//Hier de bestelling afronden en de status op betaald zetten.
//$payment = Mollie::api()->payments->get($request->id);
// if (! $request->has('id')) {
// return;
// }
// $payment = Mollie::api()->payments()->get($request->id);
// if ( $payment->metadata->isSingleProduct == true ) {
// return redirect()->to('/dashboard/orders');
// } else {
// return redirect()->to('/dashboard/orders?success=1');
// }
Log::info($id);
if ( $id == 0 ) {
return redirect()->to('/dashboard/orders?clear_cart=1');
} else {
return redirect()->to('/dashboard/orders');
}
}
Поскольку я создаю приложение SPA, используя Vue для своего интерфейса и Laravel для своего бэкенда, я хотел бы попытаться дождаться ответа функции paymentSuccess и вернуть его в представление Vue вместо перенаправления пользователя на представление с помощью помощника маршрутизатора. Теперь я не совсем уверен, как этого добиться.
Есть ли способ, которым я могу это сделать? Заранее спасибо!