Magento 2扩展GraphQL Mutation:将BraintreeInput支付随机数设为可选
要实现将BraintreeInput中的payment_method_nonce从必填改为可选,你需要通过自定义模块覆盖GraphQL Schema并调整后端验证逻辑,具体步骤如下:
1. 覆盖GraphQL Schema定义
不能直接修改vendor/paypal/module-braintree-graph-ql/etc/schema.graphqls文件(升级会覆盖),需在自定义模块中创建同名文件进行扩展:
在你的自定义模块目录下创建路径:app/code/[YourVendor]/[YourModule]/etc/schema.graphqls,并添加以下内容:
input BraintreeInput { payment_method_nonce: String is_active_payment_token: Boolean public_hash: String device_data: String vault: Boolean }
关键:移除
payment_method_nonce字段后的!符号(原Schema中该字段为String!,表示必填),同时保留所有原有字段,避免破坏其他功能。
2. 调整后端输入验证逻辑
原Braintree GraphQL模块的Resolver类会强制校验payment_method_nonce的必填性,需通过重写或插件修改这一逻辑:
方式一:使用Preference重写Resolver类
在你的自定义模块etc/di.xml中添加配置:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="PayPal\BraintreeGraphQl\Model\Resolver\SetPaymentMethodOnCart" type="[YourVendor]\[YourModule]\Model\Resolver\SetPaymentMethodOnCart" /> </config>
创建重写后的Resolver类:app/code/[YourVendor]/[YourModule]/Model/Resolver/SetPaymentMethodOnCart.php
<?php namespace [YourVendor]\[YourModule]\Model\Resolver; use Magento\Framework\GraphQl\Config\Element\Field; use Magento\Framework\GraphQl\Exception\GraphQlInputException; use Magento\Framework\GraphQl\Query\ResolverInterface; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; use PayPal\BraintreeGraphQl\Model\Resolver\SetPaymentMethodOnCart as OriginalResolver; class SetPaymentMethodOnCart extends OriginalResolver { public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) { $input = $args['input']; $paymentMethodNonce = $input['payment_method_nonce'] ?? null; // 移除原有的必填验证逻辑 // if (empty($paymentMethodNonce)) { // throw new GraphQlInputException(__('The payment method nonce is required.')); // } // 保留原Resolver的其他业务逻辑 return parent::resolve($field, $context, $info, $value, $args); } }
补充:检查支付模型的额外验证
如果Braintree支付模型(如PayPal\Braintree\Model\PaymentMethod)中也存在payment_method_nonce的必填校验,需通过插件或重写调整对应方法,确保非必填逻辑一致。
3. 启用模块并清理缓存
执行以下命令使修改生效:
bin/magento module:enable [YourVendor]_[YourModule] bin/magento setup:upgrade bin/magento cache:clean bin/magento cache:flush
4. 测试验证
使用GraphQL测试工具(如Postman、Magento内置GraphQL playground)发送setPaymentMethodOnCart mutation,不传入payment_method_nonce参数,确认请求能正常执行且无必填校验报错。
内容的提问来源于stack exchange,提问作者Mohit Verma

