Setting up the 'nativescript-stripe' plugin in your NativeScript Vue project for seamless integration

Trying to integrate the «nativescript-stripe» plugin into my Nativescript Vue app has been a challenge. The documentation and demos on the plugin's GitHub are geared towards Angular and TypeScript, making it difficult to adapt for Vue. Can anyone provide guidance on how to properly use the StandardComponent with Vue and provide insights on the parameters required by

StripeService.createPaymentSession()
?

I attempted to set <Page ref=«cartPage»> in the template and initialize paymentSession in the mounted() method:

// Import statements
var paymentSession = {};

export default {
  mounted() {
    // Not sure if this is the correct approach
    paymentSession = StripeService.createPaymentSession(
      this.$refs.cartPage,
      this.stripeItem.price,
      new Listener(this)
    );
  },

Although my stripe.service.ts mirrors the Angular demo code, I have configured the publishableKey and backendBaseURL, and have a separate class for Listener:

// Listener class
export class Listener {
  public component;
  constructor(component) {
      this.component = component;
  }
  onCommunicatingStateChanged(_isCommunicating) {
      this.component.changeDetectionRef.detectChanges();
  }
// Code from Angular demo

Despite contemplating moving the Listener class to a separate file, that doesn't seem to be the issue currently.

Encountering the error message when running the app:

CONSOLE ERROR file:///node_modules/nativescript-vue/dist/index.js:2129:21 [Vue warn]: Error in mounted hook: "TypeError: _shared_stripe_stripe_service__WEBPACK_IMPORTED_MODULE_6__["StripeService"].createPaymentSession is not a function. (In '_shared_stripe_stripe_service__WEBPACK_IMPORTED_MODULE_6__["StripeService"].createPaymentSession(this.$refs.cartPage, this.stripeItem.price, new _shared_stripe_stripe_service__WEBPACK_IMPORTED_MODULE_6__"Listener")', '_shared_stripe_stripe_service__WEBPACK_IMPORTED_MODULE_6__["StripeService"].createPaymentSession' is undefined)"

UPDATE:

After some adjustments, I managed to get the app up and running with the following setup:

ShoppingCart.vue:

// Vue component code here 

stripe.service.ts:

// Stripe service code here

However, I am currently facing an issue where nothing happens when tapping "Payment type". Despite debugging and verifying that the code is executing without errors, the action does not trigger as expected. Specifically, the method presentPaymentMethods() from the plugin seems to be running without any visible effect.

Any insights or suggestions on this would be greatly appreciated!

Answer №1

Finally, after dedicating numerous hours to the task, I successfully unraveled the solution. A huge shoutout to @Manoj for the helpful tip!

stripe.service.ts:

import { StripeAddress, StripeBackendAPI, StripeConfig, StripeCustomerSession, StripePaymentListener, StripePaymentSession, StripeShippingAddressField, StripeShippingMethod } from "nativescript-stripe/standard";
import * as httpModule from "tns-core-modules/http";

// 1) To initiate this demo, visit https://dashboard.stripe.com/account/apikeys and retrieve your "Test Publishable Key" (e.g., pk_test_abcdef). Paste it below.
export const publishableKey = "pk_test_yours";

// 2) Optionally, for saving user payment details, deploy the backend from https://github.com/stripe/example-ios-backend to Heroku. Paste your Heroku URL (e.g., https://blazing-sunrise-1234.herokuapp.com ) below.
const backendBaseURL = "https://yours.herokuapp.com/";

// 3) To enable Apple Pay, create an Apple Merchant ID as per the instructions at https://stripe.com/docs/apple-pay/apps Paste it below (e.g., merchant.com.yourappname).
const appleMerchantID = "";

// Listener class
export class Listener {
  public component;
  constructor(component) {
    this.component = component;
  }
  // Additional methods here
}

// StripeService class
export class StripeService implements StripeBackendAPI {
  // Additional methods here
}

Payment.vue:

<template>
  // Vue template code here
</template>

<script>
// TypeScript code here
</script>

Ensure that TypeScript is installed using the command tns install typescript.

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

Using Typescript to inherit from several classes with constructors

I am trying to have my class extend multiple classes, but I haven't been able to find a clean solution. The examples I came across using TypeScript mixins did not include constructors. Here is what I am looking for: class Realm { private _realms: C ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

When employing CDK to configure an SNS topic Policy Statement with actions limited to ["sns:*"], the CloudFormation output may display a warning message stating "Policy statement action is not within the service scope."

Encountering an issue when attempting to reference all SNS actions with * in CDK. const MyTopicPolicy = new sns.TopicPolicy(this, 'MyTopicSNSPolicy', { topics: [MyTopic], }); MyTopicPolicy.document.a ...

Update current properties of objects

I'm feeling like I'm going crazy and could really use some assistance. My predicament involves a function that looks like this: private generateTimeObject(firstObject: someInterface, secondObject?: someInterface) { let firstTime; let secondTi ...

I'm looking for a way to merge the functionalities of tsc build watch and nodemon into a single Node.js

Currently, I have two scripts in my code: "scripts": { "build": "tsc -p . -w", "watchjs": "nodemon dist/index.js" } I need to run these two scripts simultaneously with one command so that the build ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

The template literal expression is invalid due to the "string | null" type when sending authorization

While working on implementing authorization, I encountered an error from Ts-eslint stating that there was an "Invalid type 'string | null' of template literal expression" when trying to execute the functionality. The data being retrieved from lo ...

How can I properly containerize an Express Gatsby application with Docker?

SOLUTION: I am currently working on a project involving an express-gatsby app that needs to be built and deployed using GitHub Actions. To deploy it on Heroku, I have learned that containerizing the app is necessary. As a result, I have created a Dockerfil ...

"Dealing with conflicts between RMQ and TypeORM in a NestJS

Every time I try to use TypeOrm, RMQ crashes. I can't figure out why. Utilizing the library golevelup/nestjs-rabbitmq has been a struggle for me. I've spent 7 hours trying to resolve this issue. @Module({ imports: [ ConfigModule.f ...

Using Material UI Slider along with Typescript for handling onChange event with either a single number or an

Just diving into Typescript and encountered an issue with a Material UI Slider. I'm trying to update my age state variable, but running into a Typescript error due to the typing of age being number and onChange value being number | number[]. How can I ...

Steps to configure Visual Studio Code to automatically open the original TypeScript file located in the "src" folder when a breakpoint is hit in a Node.js application

I am currently working on a CLI node application and using VSCode to debug it. Everything seems to be working fine, except for one annoyance: when I hit a breakpoint, VSCode opens the source map file instead of the actual TypeScript file located in my "src ...

Error: Unable to retrieve the value of 'secret' as it is undefined when attempting to assign a response cookie in Express framework

Today's operation that I've carried out countless times seems to be going awry. For some reason, I am unable to set a refresh token cookie using Express. Here is the error message in full /home/me/Code/apGymBE/node_modules/express/lib/response.j ...

Utilize a fresh function in Angular to retrieve and store data from a URL into a variable

Currently, I am attempting to utilize Angular in order to retrieve data from a link upon clicking a button. As a newcomer to Angular with only 2 days experience, my knowledge is quite limited. What I aim to achieve is triggering the loading of JSON data w ...

Sending returned values from a promise to the calling function in Angular

I have a created a promise to retrieve values from a service and then assign them to variables trans and confidence, which should be used as transcript and conf in the save_data function. How can I return these values to the calling function and ensure tha ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

Utilizing a conditional ngIf statement in HTML or incorporating a variable within typescript for logical operations

When working with our application, we often need to display or hide a button based on specific logic. Where do you think it is best to define this logic and why? In HTML: *ngIf='logic goes here' //Or *ngIf='someBoolean' and in Type ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

Do type declaration files for NPM packages have to be in the .d.ts format?

I believe it is feasible to include type declarations in any typescript file like '.d.ts', '.ts', or '.tsx'. However, I have observed that the type declaration files for most npm packages are .d.ts files. Is this a requireme ...

Differentiate between function and object types using an enum member

I'm currently experimenting with TypeScript to achieve narrowed types when dealing with index signatures and union types without explicitly discriminating them, such as using a switch case statement. The issue arises in the code snippet below when at ...