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

Time:10-21

I am building this payment request object as follows

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']

And using this paymentRequest in the html as follows

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

My Question:

I want to dynamically add the properties inside request object dynamically. For example I want to add property "billingAddressRequired = true" at some cases alone and for other cases I don't require it. So my request object will not contain "billingAddressRequired" property.

CodePudding user response:

{billingAddressRequired?:Boolean} use something like this for interface .

for dynamically adding property if(someCondition) request['billingAddressRequired']=true;

Simply like this

CodePudding user response:

You can achieve this by updating the paymentRequest property based on whatever condition you require.

See 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;
  }
}

In the example above, the billingAddressRequired and billingAddressParameters are set if a checkbox is checked, and they're removed if the checkbox isn't checked.

  • Related