-1

When the payment widget is called, after a successful transaction, the pay function should be executed, but in the console I see the error this.pay() is not a function. What could be the problem?

A widget function

  openWidget() {
    // @ts-ignore
    let widget = new PaytureWidget({
      Key : "Merchant",
      Amount : this.model.sum,
      Product : "Payment №1",
      Domain : 2,
      OnTransactionCompleted : function(success: any) { 
        this.pay()
      }
    })
  }

And pay() if needed:

  async pay() {
    const mapProduct = (product: ShoppingCartProduct): UserProduct => {
      return {
        productId: product.id,
        count: product.multiplicator,
        price: product.price
      }
    }

    const userProducts = this.sumupProducts.map(mapProduct)
    const accountBalance = await this.userProductsDataService.addProducts(userProducts);
    if (accountBalance !== -1) {

      this.paymentEventService.emitSuccess(accountBalance);
      this.model.products = this.model.products.filter(x => !x.checked);
      this.sumupProducts = [];
      this.model.sum = this.getShoppingCartSum();
      this.eventService.emit(StarOneEventType.ChangedNumberOfProductsInShoppingCart);
    } else {
      this.paymentEventService.emitFail("Payment Fail");
    }
  }
  • 2
    try using a arrow function ```OnTransactionCompleted: (success: any) => { this.pay() }``` – roapp Dec 14 '22 at 10:49

2 Answers2

3

The problem is that the this keyword inside the OnTransactionCompleted callback function refers to the callback function itself, rather than the component where the openWidget function is defined. This means that this.pay is not a valid method because it doesn't exist on the callback function.

One way to fix this issue would be to use an arrow function for the OnTransactionCompleted callback, like this:

  openWidget() {
  // @ts-ignore
  let widget = new PaytureWidget({
    Key : "Merchant",
    Amount : this.model.sum,
    Product : "Payment №1",
    Domain : 2,
    OnTransactionCompleted : (success: any) => {
      this.pay();
    }
  });
}

Arrow functions use the value of the this keyword from the surrounding context, so in this case, this will refer to the component where the openWidget function is defined, and this.pay will be a valid method.

1

Try this one

OnTransactionCompleted : (success: any) => { 
    this.pay()
  }