选择离线付款后如何将订单状态更改为已付款?

时间:2018-07-04 14:27:43

标签: symfony symfony4 sylius

使用稳定的Sylius 1.2.0,在选择了离线付款方式后,如何将订单标记为已付款?

尝试过使用sylius_order_payment状态机的回调,但是在任何过渡上似乎都不会触发:

winzou_state_machine:
    sylius_order_payment:
        callbacks:
            after:
                set_order_paid:
                    on: ['complete']
                    do: ['@AppBundle\Payment\StateMachine\Callback\CallbackClass', 'updateOrder']
                    args: ['object']

是否使用了状态机?也许我使用的是错误的。欢迎任何建议。谢谢您的耐心等候。

更新1

明天我将尝试使用文档中的Completing a Payment with a state machine transition一章。我正在考虑将这段代码放在事件监听器中,以监听 Order创建的资源事件,尽管状态机回调听起来是一个更好的解决方案。

1 个答案:

答案 0 :(得分:5)

最终使其正常工作:

state_machine.yml

winzou_state_machine:
    sylius_order_checkout:
        callbacks:
            after:
                app_order_complete_set_paid:
                    on: ['complete']
                    do: ['@AppBundle\Order\StateMachine\Callback\OrderCompleteSetPaidCallback', 'setPaid']
                    args: ['object']

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: true

    AppBundle\Order\StateMachine\Callback\OrderCompleteSetPaidCallback: ~

OrderCompleteSetPaidCallback.php

<?php

namespace AppBundle\Order\StateMachine\Callback;

use SM\Factory\FactoryInterface;
use AppBundle\Infrastructure\CommandBus\CommandBus;
use AppBundle\Order\SetPaid\SetPaidCommand;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Payment\PaymentTransitions;

final class OrderCompleteSetPaidCallback
{
    private $stateMachineFactory;

    public function __construct(FactoryInterface $stateMachineFactory)
    {
        $this->stateMachineFactory = $stateMachineFactory;
    }

    public function setPaid(OrderInterface $order): void
    {
        if (!($lastPayment = $order->getLastPayment())) {
            return;
        }

        if ('cash_on_delivery' === $lastPayment->getMethod()->getCode()) {
            $this->transition($order);
        }
    }

    private function transition(OrderInterface $order): void
    {
        $stateMachine = $this->stateMachineFactory->get($order, OrderPaymentTransitions::GRAPH);
        $stateMachine->apply(OrderPaymentTransitions::TRANSITION_PAY);

        $payment = $order->getLastPayment();

        $stateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH);
        $stateMachine->apply(PaymentTransitions::TRANSITION_COMPLETE);
    }
}