Magento2 - 使用Paypal结算协议创建自定义订单(“强制参数缺少referenceId错误”)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Magento2 - 使用Paypal结算协议创建自定义订单(“强制参数缺少referenceId错误”)相关的知识,希望对你有一定的参考价值。

我正在创建一个自定义模块,以编程方式使用paypal结算协议创建订单作为付款方式。以下是我使用的订单创建代码。

<?php

namespace VendorModuleModelSubscriptionOrder;

class Create
{
    public function __construct(
        MagentoFrameworkAppHelperContext $context,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoCatalogModelProductFactory $productFactory,
        MagentoQuoteModelQuoteManagement $quoteManagement,
        MagentoCustomerModelCustomerFactory $customerFactory,
        MagentoCustomerApiCustomerRepositoryInterface $customerRepository,
        MagentoSalesModelServiceOrderService $orderService,
        MagentoQuoteApiCartRepositoryInterface $cartRepositoryInterface,
        MagentoQuoteApiCartManagementInterface $cartManagementInterface,
        MagentoQuoteModelQuoteAddressRate $shippingRate
    ) {
        $this->_storeManager = $storeManager;
        $this->_productFactory = $productFactory;
        $this->quoteManagement = $quoteManagement;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->orderService = $orderService;
        $this->cartRepositoryInterface = $cartRepositoryInterface;
        $this->cartManagementInterface = $cartManagementInterface;
        $this->shippingRate = $shippingRate;
    }
    /**
     * Create Order On Your Store
     *
     * @param array $orderData
     * @return int $orderId
     *
     */
    public function createOrder($orderData) {

        //init the store id and website id @todo pass from array
        $store = $this->_storeManager->getStore();
        $websiteId = $this->_storeManager->getStore()->getWebsiteId();
        //init the customer
        $customer=$this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderData['email']);// load customet by email address
        //check the customer
        if(!$customer->getEntityId()){
            //If not avilable then create this customer
            $customer->setWebsiteId($websiteId)
                ->setStore($store)
                ->setFirstname($orderData['shipping_address']['firstname'])
                ->setLastname($orderData['shipping_address']['lastname'])
                ->setEmail($orderData['email'])
                ->setPassword($orderData['email']);
            $customer->save();
        }
        //init the quote
        $cart_id = $this->cartManagementInterface->createEmptyCart();
        $cart = $this->cartRepositoryInterface->get($cart_id);
        $cart->setStore($store);
        // if you have already buyer id then you can load customer directly
        $customer= $this->customerRepository->getById($customer->getEntityId());
        $cart->setCurrency();
        $cart->assignCustomer($customer); //Assign quote to customer
        //add items in quote
        foreach($orderData['items'] as $item){
            $product = $this->_productFactory->create()->load($item['product_id']);
            $cart->addProduct(
                $product,
                intval($item['qty'])
            );
        }
        //Set Address to quote 
        $cart->getBillingAddress()->addData($orderData['shipping_address']);
        $cart->getShippingAddress()->addData($orderData['shipping_address']);
        // Collect Rates and Set Shipping & Payment Method
        $this->shippingRate
            ->setCode('freeshipping_freeshipping')
            ->getPrice(1);
        $shippingAddress = $cart->getShippingAddress();
        //@todo set in order data
        $shippingAddress->setCollectShippingRates(true)
            ->collectShippingRates()
            ->setShippingMethod('flatrate_flatrate'); //shipping method
        $cart->getShippingAddress()->addShippingRate($this->shippingRate);
        $cart->setPaymentMethod('paypal_billing_agreement'); //payment method
        //@todo insert a variable to affect the invetory
        $cart->setInventoryProcessed(false);
        // Set sales order payment
        $cart->getPayment()->importData(['method' => 'payapal_billing_agreement,'reference_id' => 'B-RTRHFHs8428355236']);
        // Collect total and saeve
        $cart->collectTotals();
        // Submit the quote and create the order
        $cart->save();
        $cart = $this->cartRepositoryInterface->get($cart->getId());
        $order_id = $this->cartManagementInterface->placeOrder($cart->getId());
        return $order_id;
    }
}

当我将付款方式更改为“免费”时,它可以正常工作。 Paypal结算协议付款方式需要额外的数据,因为我检查结帐时的实际结算协议流程。

{method: "paypal_billing_agreement", additional_data: {…}}
additional_data:{ba_agreement_id: "5"}
method:"paypal_billing_agreement"

我甚至试图为getpayment方法添加相同的导入数据,但同样的问题仍然存在。 callDoReferenceTransaction()的请求post已正确设置所有必需参数,但REFERENCEID设置为NULL。

注意:使用为magento 2.1提供的默认的PayPal NVP API。

抛出的异常是:

1 exception(s):
Exception #0 (MagentoFrameworkExceptionLocalizedException): PayPal gateway has rejected request. ReferenceID : Mandatory parameter missing (#81253: Missing Parameter)

.

我错过了什么?

在此先感谢您的帮助。

答案

所以我找到了解决方案,

先决条件,首先我必须从后端启用结算协议订单。

为此,我在Observer中进行了更改,默认情况下在module-paypal中将“is_allowed”设置为false为true。

然后在代码中进行以下更改以使用引用事务创建订单,

$cart->setPaymentMethod('paypal_billing_agreement'); //payment method
$cart->setInventoryProcessed(false);
// Set sales order payment

$cart->getPayment()->setAdditionalInformation("ba_agreement_id","1");//To point the correct billing agreement in billing agreement table.

$cart->getPayment()->importData(['method' => 'paypal_billing_agreement,'reference_id' => 'B-RTRHFHs8428355236']);
// Collect total and saeve
$cart->collectTotals();
// Submit the quote and create the order
$cart->save();

并且当然用try catch包装来处理异常

以上是关于Magento2 - 使用Paypal结算协议创建自定义订单(“强制参数缺少referenceId错误”)的主要内容,如果未能解决你的问题,请参考以下文章

PayPal定期付款 - 结算计划是否意味着有多个结算协议?

无法批准有效的贝宝结算协议

Paypal 结算协议不快速支付?

使用 API 创建 Paypal 计费协议

已收到帐单协议付款的 Paypal Webhook?

结算协议 ID 或交易 ID 无效