Adding properties to request object on-the-fly - Google Pay [Typescript]

Here is how I am constructing the payment request object:

paymentRequestObject: 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 here is how I am using the payment request in my HTML code:

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

My Inquiry:

I am looking to dynamically add properties inside the request object. For example, I may need to include the property "billingAddressRequired = true" in certain cases only while excluding it in others. How can I achieve this flexibility with my request object?

Answer №1

To implement this functionality, simply update the paymentRequest property based on your specific conditions.

For a practical demonstration, refer to this 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 this scenario, the billingAddressRequired and billingAddressParameters are conditionally included based on a checkbox's state.

Answer №2

{checkIfBillingAddressIsRequired?:Boolean} implement an interface similar to this.

To dynamically include a property, if(conditionMet) request['checkIfBillingAddressIsRequired']=true;

It can be done as easy as that

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent HTTP using AsyncValidator when the value is empty

I have developed a custom AsyncValidator to verify the uniqueness of a userName. Inspired by this tutorial, I have implemented a delay of 500ms. However, I am facing a challenge in preventing the HTTP service call if the input value does not meet a speci ...

Tips for dividing by a large number

I am currently attempting the following: const numerator = 268435456; const denominator = 2 ** 64; const decimalFraction = numerator / denominator; In order to achieve this, I have experimented with utilizing the code provided in this link: : const rawVal ...

Encountered a problem while attempting to build with ng build --prod. No issues when using ng serve or excluding

My project was working smoothly with ng build --prod until I decided to update the TypeScript version from 2.72 to 2.92 in my package.json file. Now, after the update, an error message pops up: ERROR in Cannot read property 'Symbol(Symbol.iterator ...

removing the mapStateToProps function will result in an undefined value

I am new to React and I'm in the process of converting a class component to functional components using hooks. I need some guidance on safely removing 'mapStateToProps' without encountering undefined errors. I have two pages, A.js and B.js. ...

Error with React, key must be unique. What's the issue?

What is causing the issue with unique keys? To resolve the problem, ensure that each list item has a unique key. For example, if we have x_values = {'male':[1,2,3], 'female':[2,3,4]} the keys should be : 'mean-male', ' ...

Is it possible to retrieve a value obtained through Request.Form?

Within my Frontend, I am passing an Object with a PersonId and a FormData object. const formData = new FormData(); for (let file of files){ formData.append(file.name, file,); } formData.append('currentId',this.UserId.toString()); const upl ...

Prevent the Vue page from loading until the data has been fetched successfully

I'm in the process of finding a way to prevent my page from loading until my fetch task is completed. I'm facing some issues that need to be addressed: I have to re-fetch the data each time because I can't reuse the same data. (Changing vie ...

Notification from the background has been received and parameters have been restored

Sending a post request from "angular->port 4200" to "expressjs server->port 8000". Referencing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts Encountering two errors: 1) Undefined ...

Leverage ng2-charts along with a loading component during the AfterViewInit lifecycle hook

Currently, I am working on a web page that contains various charts. My focus right now is on developing a simple loader as shown below: <div *ngIf="loading === true; else elseBlock" class="container"> <div class="grid-pulse la-3x"> </di ...

Move after a specified amount of time

I'm struggling to implement a 6-second redirect in my Angular application that will take users to the homepage. The only resources I've found on this topic are for AngularJS. --------------------UPDATE--------------- Here are my current routes: ...

What could be causing routerLink to malfunction despite correct configuration?

Is routerLink properly placed in the view? <p><a routerLink="/registration" class="nav-link">Register</a></p> Checking my app.module import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

Function useAppDispatch is missing a return type

.eslintrc.js module.exports = { root: true, extends: [ '@react-native-community', 'standard-with-typescript', 'plugin:@typescript-eslint/recommended', 'plugin:jest/recommended', 'plugin:p ...

Drizzle-ORM provides the count of items in a findMany query result

Hello there, I'm currently experimenting with the Drizzle ORM and imagine I have this specific query const members = await trx.query.memberTable.findMany({ with: { comments:true } }) I'm wondering how I can retrieve the total count of me ...

Tips for resetting the mat-progress-spinner to its initial state

I want to use the spinner as a timer and switch the progress direction. Currently, it moves clockwise when going from 0 to 100, but I need it to go counterclockwise from 100 (equivalent to 15 minutes or 900 seconds) to 0 (when time runs out). <mat-prog ...

The width of the Bootstrap tooltip changes when hovered over

Currently, I am facing a peculiar issue with my angular web-application. Within the application, there is a matrix displaying data. When I hover over the data in this matrix, some basic information about the object pops up. Strangely, every time I hover ov ...

Angular: Converting the outcome of a request to an observable

When working on my project, I decided to tackle it module by module to ensure each part had access to the user. However, as I refine the project, I'm encountering a situation where multiple API requests are being made for the same purpose (user info) ...

Encountering the error message "Undefined. Please implement using the following snippet" while running a protractor cucumber typescript feature file

Currently, I am utilizing Protractor with TypeScript and Cucumber for automation purposes. After going through some informative articles, I have successfully incorporated feature files and step definitions into my end-to-end project. Below is the structur ...

The Angular4 router.navigate function appears to be unresponsive and fails to perform any actions

I have implemented conditional navigation based on the customer's role in the system. Here is an example of how it works: this.GetQuickStartStatus() .subscribe(data => { if(data.isActive){ ...

Is it possible to customize the appearance of a toast notification using Toastr beyond the default settings? If so, what options are available for creating

Working with Angular 9 and ngx-toastr has presented me with an interesting challenge. I am tasked with creating custom toast styles that differ significantly from the default ones provided by toastr. Each toast in the set will have unique border colors, f ...