Incorporating Ionic v3 with the latest StripeJS/Stripe Elements version 7.26.0

I have encountered two separate issues while trying to integrate the new version of Stripe into my Ionic v3 app. (Please refrain from suggesting an upgrade to Ionic v5, as it is currently not feasible for our team at this time!)

Within my ionDidLoad function, I have the following code:

var stripe = Stripe('pk_test_OwV8RfgF7JQp1FEW3OfqmPpz');
  var elements = stripe.elements();
  var style = {
    base: {
      color: "#32325d",
    }
  };

  var card = elements.create("card", { style: style });
  card.mount("#card-element");

  card.addEventListener('change', ({error}) => {
    const displayError = document.getElementById('card-errors');
    if (error) {
      displayError.textContent = error.message;
    } else {
      displayError.textContent = '';
    }
  });

  var form = document.getElementById('payment-form');

  form.addEventListener('submit', function(ev) {
    ev.preventDefault();

    stripe.confirmCardPayment( this.clientSecret, {
      payment_method: {
        card: card,
        billing_details: {
          name: 'Jenny Rosen'
        }
      }
    }).then(function(result) {
      if (result.error) {
        // Show error to your customer (e.g., insufficient funds)
        console.log(result.error.message);
      } else {
        // The payment has been processed!
        if (result.paymentIntent.status === 'succeeded') {

          /****  this.postOrder(); */

          // Show a success message to your customer
          // There's a risk of the customer closing the window before callback
          // execution. Set up a webhook or plugin to listen for the
          // payment_intent.succeeded event that handles any business critical
          // post-payment actions.
        }
      }
    });
  });

Issue #1: var stripe = Stripe('pk_test_*******************') I am seeing a red squiggly line under "Stripe('pk_test...)" in VSCode. The error message states "Value of type 'typeof Stripe' is not callable. Did you mean to include 'new'?ts(2348)". Despite searching online, I haven't been able to resolve this issue. I attempted declaring "Stripe" but it did not alleviate the problem. I understand that Stripe is a reference in StripeJS.

Issue #2: stripe.confirmCardPayment( this.clientSecret, {... Once again, a red squiggly line appears, this time under "this.clientSecret". The value of this.clientSecret is set in my app based on the return of the paymentIntents call to my server as shown below:

this.inStockService.paymentIntentRoutine(this.ot).subscribe(res => {
        this.clientSecret = res;
      });

The error from VSCode reads "Property 'clientSecret' does not exist on type 'HTMLElement'.ts(2339)". I am still learning and struggling to grasp why this error is occurring.

If anyone can provide assistance in resolving these issues, I would greatly appreciate it.

Answer №1

One of the main issues to address is:

If you have included Stripe in your project by using

<script src="https://js.stripe.com/v3/"></script>
in your index.html file, the Stripe object can be accessed through the window global object as window.Stripe. It is important to declare Stripe in the component after importing it:

> declare var Stripe: any;

Another approach is to access Stripe through window['Stripe'] in your code, although this may not be the best solution.

To avoid TypeScript problems, consider installing types for the specific version of Stripe you are using. For example, for version 3, you can use:

npm install --save @types/stripe-v3
.

Additionally, another issue to tackle is:

Utilize fat arrow functions to prevent the 'this' keyword from referring to the scope of an anonymous function:

form.addEventListener('submit', ev => {

    ev.preventDefault();

    stripe.confirmCardPayment( this.clientSecret, {
      payment_method: {
        card: card,
        billing_details: {
          name: 'Jenny Rosen'
        }
      }
    }).then( result => {
      if (result.error) {
        // Display error message to the customer (e.g., insufficient funds)
        console.log(result.error.message);
      } else {
        // The payment has been processed successfully!
        if (result.paymentIntent.status === 'succeeded') {

          /****  this.postOrder(); */

          // Show a success message to the customer
          // Note: There's a risk of the customer closing the window before the callback function is executed. Consider setting up a webhook or plugin to handle post-payment actions.
        }
      }
    });
  });

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

Steer clear of including numerous variable values in Angular 2 while adjusting the class of selected items

Here's a question from someone who is new to Angular 2 and looking for an efficient way to change the active CSS class of tabs without using the router: activeTab: string; switchActiveTab(newTab: string) { this.activeTab = newTab; } <div clas ...

The absence of Index.ts in the TypeScript compilation cannot be resolved by simply including it

Upon integrating @fireflysemantics/slice into my Angular project, I encountered the following error: ERROR in ./node_modules/@fireflysemantics/slice/index.ts Module build failed (from ./node_modules/@ngtools/webpack/src/index.js): Error: /home/ole/Temp/fs ...

Error: The function being called in <class> is not recognized as a function

I have a unique situation with my component setup export class Component1Component implements OnInit { public greetings: string =""; constructor(private greeter: Greeter) { } ngOnInit() { this.greetings = this.greeter.sayHello(); } } The structur ...

What is the reason for Typescript's compatibility with WScript?

Recently, I decided to install Typescript in order to get WScript intellisense in VScode. After setting it up, I was able to achieve the desired intellisense. However, I encountered an issue when compiling a Typescript file containing a WScript method usin ...

A backend glitch is exposed by NextJS in the web application

Currently, I am utilizing Strapi for my backend and have created a small script to handle authorization for specific parts of the API. Additionally, I made a slight modification to the controller. 'use strict'; const { sanitizeEntity } = require( ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

Swap out a specific object within an observable array by comparing object properties

Currently, I am retrieving an observable array of custom IPix objects (Observable<IPix[]>) from a database using an API. After that, I update a record in the database by sending an edited version of the IPix object back to the API through a PUT reque ...

Having trouble with an unexpected value in your Angular2 Service? Don't forget to add

I encountered an error in my Angular2 app: Error: (SystemJS) Unexpected value 'ReleasesService' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Here is my AppModule code: import { NgModule } fr ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

The best approach to typing a FunctionComponent in React with typescript

I'm diving into the world of React and TypeScript for the first time. Could someone verify if this is the correct way to type a FunctionComponent? type ModalProps = { children: ReactElement<any>; show: boolean; modalClosed(): void; }; co ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

Navigate to the logout page automatically when closing the final tab

In order to comply with the requirement, I need to log out the user when they close the last tab on the browser. ngOnInit() { let counter: any = this.cookieService.get('screenCounterCookie'); counter ? ++counter : (counter = & ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows: ➜ typescript-project yarn test yarn run v1.22.17 warning package.json: No license field $ ...

What could be the reason for the tsc command not displaying compilation errors when compiling a particular file?

My file, titled app.ts, contains the following code snippet: interface Foo { bar:String; } const fn = (foo? :Foo) => foo.bar; When I run tsc from the root folder with strict:true in my tsconfig.json file, I receive an error message like this ...

An error has been detected: An unexpected directive was found. Kindly include a @NgModule annotation

I am encountering an issue while trying to import a class into a module in my Ionic/Angular app. Upon attempting to release, the following error message appears: ERROR in : Unexpected directive 'SeedModalPage in /home/robson/Lunes/repositories/bolunes ...

"Resulting in 'undefined' due to an asynchronous function call

Encountering an issue with async method implementation. In my authServices, there is a loginWithCredential function which is asynchronous: async loginWithCredential(username, password){ var data = {username: username, password: password}; api.pos ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

The export "hasInjectionContext" is not provided by the source file "node_modules/vue-demi/lib/index.mjs", but it is being requested in the file "node_modules/pinia/dist/pinia.mjs"

Every time I launch my program, the console displays an error message stating that "hasInjectionContext" is not exported by "node_modules/vue-demi/lib/index.mjs", imported by "node_modules/pinia/dist/pinia.mjs" at line 6:9. I ...

What is the best way to incorporate Typescript React Components across various projects?

I'm venturing into developing an npm package that involves several react components implemented with typescript. As a newcomer to react and npm, I apologize if my query seems basic. Despite researching online, there isn't much information on this ...