简体   繁体   中英

Validate Payment Method in Magento 2

I want to check whether a customer is allowed to use one of the activated payment methods.

For example:

If the customer had enabled "Cash on Delivery", he should see the method but I can't find anything similar in the code.

In Magento 1 there was:

public function isAvailable()

Is there any similar way to do it with Magento 2 ?

There are 2 approaches you could take:

Observer

If you take a look at \\Magento\\Payment\\Model\\Method\\AbstractMethod (the parent class of \\Magento\\OfflinePayments\\Model\\Cashondelivery ) in the isAvailable method, you will find that it dispatches the payment_method_is_active event which could be used to performs some additional logic (such as determine if a customer had enabled the specific method or not):

$this->eventManager->dispatch( 'payment_method_is_active', [ 'result' => $checkResult, 'method_instance' => $this, 'quote' => $quote ] );

Plugin

Since isAvailable is a public method, you could add a plugin to the method. Whether you use before, after, or around depends on your specific needs. However, a good place for learning how to do this is the Magento DevDocs site: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM