Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AddBillingAgreementToSessionObserver.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
19  protected $agreementFactory;
20 
24  protected $checkoutSession;
25 
32  public function __construct(
33  \Magento\Paypal\Model\Billing\AgreementFactory $agreementFactory,
34  \Magento\Checkout\Model\Session $checkoutSession
35  ) {
36  $this->agreementFactory = $agreementFactory;
37  $this->checkoutSession = $checkoutSession;
38  }
39 
44  public function execute(EventObserver $observer)
45  {
47  $orderPayment = $observer->getEvent()->getPayment();
48  $agreementCreated = false;
49  if ($orderPayment->getBillingAgreementData()) {
50  $order = $orderPayment->getOrder();
52  $agreement = $this->agreementFactory->create()->importOrderPayment($orderPayment);
53  if ($agreement->isValid()) {
54  $message = __('Created billing agreement #%1.', $agreement->getReferenceId());
55  $order->addRelatedObject($agreement);
56  $agreement->addOrderRelation($order);
57  $this->checkoutSession->setLastBillingAgreementReferenceId($agreement->getReferenceId());
58  $agreementCreated = true;
59  } else {
60  $message = __('We can\'t create a billing agreement for this order.');
61  }
62  $comment = $order->addStatusHistoryComment($message);
63  $order->addRelatedObject($comment);
64  }
65  if (!$agreementCreated) {
66  $this->checkoutSession->unsLastBillingAgreementReferenceId();
67  }
68  }
69 }
$order
Definition: order.php:55
__()
Definition: __.php:13
$message
__construct(\Magento\Paypal\Model\Billing\AgreementFactory $agreementFactory, \Magento\Checkout\Model\Session $checkoutSession)