动态添加属性到请求对象 - Google 支付 [Typescript]

Dynamically add properties to request object - Google Pay [Typescript]

我正在构建这个支付请求对象如下

paymentRequest: google.payments.api.PaymentDataRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [
  {
    type: 'CARD',
    parameters: {
      allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
      allowedCardNetworks: ['AMEX', 'VISA', 'MASTERCARD'],
      billingAddressRequired: true,
      billingAddressParameters:{
        format:'FULL',
        phoneNumberRequired:true
      }
    },
    tokenizationSpecification: {
      type: 'PAYMENT_GATEWAY',
      parameters: {
        gateway: 'example',
        gatewayMerchantId: 'exampleGatewayMerchantId'
      }
    }
  }
],
merchantInfo: {
  merchantId: '12345678901234567890',
  merchantName: 'Demo Merchant'
},
transactionInfo: {
  totalPriceStatus: 'FINAL',
  totalPriceLabel: 'Total',
  totalPrice: '0.10',
  currencyCode: 'EUR',
  countryCode: 'BE'
},
callbackIntents: ['PAYMENT_AUTHORIZATION']

并在 html 中使用此 paymentRequest 如下

<google-pay-button
    environment="TEST"
    buttonType="buy"
    buttonColor="black"
    [paymentRequest]="paymentRequest"
    (loadpaymentdata)="onLoadPaymentData($event)"
    (error)="onError($event)"
    [paymentAuthorizedCallback]="onPaymentDataAuthorized"></google-pay-button>

我的问题:

我想在请求对象中动态添加属性。例如,我想在某些情况下单独添加 属性 "billingAddressRequired = true",而在其他情况下我不需要它。所以我的请求对象将不包含“billingAddressRequired”属性.

{billingAddressRequired?:Boolean} 使用类似这样的接口。

用于动态添加 属性 如果(某些条件) 请求['billingAddressRequired']=真;

就这样

您可以根据需要的任何条件更新 paymentRequest 属性 来实现此目的。

参见StackBlitz example

onBillingClick(event) {
  console.log('request billing', event.target.checked);
  if (event.target.checked) {
    this.paymentRequest.allowedPaymentMethods[0].parameters.billingAddressRequired = true;
    this.paymentRequest.allowedPaymentMethods[0].parameters.billingAddressParameters =
      {
        format: 'FULL',
        phoneNumberRequired: true,
      };
  } else {
    delete this.paymentRequest.allowedPaymentMethods[0].parameters
      .billingAddressRequired;
    delete this.paymentRequest.allowedPaymentMethods[0].parameters
      .billingAddressParameters;
  }
}

在上面的示例中,如果复选框被选中,billingAddressRequiredbillingAddressParameters 将被设置,如果复选框未被选中,它们将被删除。