简体   繁体   中英

how to redirect back to my ionic app from a payment site

Good everyone. Please I need your assistance. I am using a payment gateway that needs to redirect back to my ionic app after a successful transaction. But after a successful transaction, I am having this error message "can't post to localhost:8100/home" but when I use a site URL for example( https://siteurl.com ), it works by redirecting to the specified site. I don't know where I am getting it wrong and what will be the callback URL to my app. Here is my code. Thanks.

completePurchase() {
    this.loadingCtrl.create({
      message: "Order Processing...",
      showBackdrop: true
    }).then((overlay) => {
      this.loading = overlay;
      this.loading.present();
      let currentCustomerId = localStorage.getItem('currentUserId');
      if (this.paymentGatwayId == "tbz_rave") {
        this.rave.init(false, "PUBLIC_KEY") //true = production, false = test
          .then(_ => {
            var paymentObject = this.ravePayment.create({
              customer_email: this.user.email,
              amount: this.totalPrice,
              customer_firstname: `${this.user.first_name}`,
              customer_lastname: `${this.user.last_name}`,
              customer_phone: `${this.user.billing.phone}`,
              currency: "NGN",
              txref: "rave-1234550",
              redirect_url: "http://localhost:8100/home",
              meta: [{
                metaname: "flightID",
                metavalue: "AP1234"

              }]
            })
            this.rave.preRender(paymentObject)
              .then(secure_link => {
                secure_link = secure_link + " ";
                const browser: InAppBrowserObject = this.rave.render(secure_link, this.iab);
                browser.on("loadstart")
                  .subscribe((event: InAppBrowserEvent) => {
                    if (event.url.indexOf('http://localhost:8100/home') != -1) {

                      if (event.url.includes("payment_successfull")) {

                        browser.close();

                        console.log("Transaction Succesful");

                        // Place order after payment successfull
                          let orderObj = {};
                    orderObj['payment_method'] = this.paymentGatwayId;
                    orderObj['payment_method_title'] = this.paymentGatewayTitle;
                    orderObj['customer_id'] = currentCustomerId;
                    this.platform.ready().then(() => {
                      this.address = {
                        first_name: this.user.first_name,
                        last_name: this.user.last_name,
                        address_1: this.user.billing.address_1,
                        city: this.user.billing.city,
                        address_2: this.user.billing.address_2,
                        phone: this.user.billing.phone,
                      }
                      orderObj['billing'] = this.address;
                      orderObj['line_items'] = this.baseProducts;
                      this.WC.placeOrder(orderObj).then(async (respData) => {
                        this.storage.clear();
                        this.storage.set('currentOrderData', respData);
                        console.log(orderObj);
                        //navigate after successful placing of other
                        const alert = await this.alertCtrl.create({
                          cssClass: 'my-custom-class',
                          header: 'Status',
                          message: ' <strong>Transaction successful</strong>!',
                          buttons: [
                            {
                              text: 'Okay',
                              handler: () => {
                                this.route.navigate(['/menu/order']);
                              }
                            }
                          ]
                        });

                        await alert.present()

                        this.route.navigate(['/menu/order']);
                      }).catch((error) => {
                        console.log('Problem with placing order', error);
                      });
                    });

                      } else {
                        browser.close();
                        console.log("Transaction fail");

                      }
                      browser.close()
                    }
                  })
              }).catch(error => {
                // Error or invalid paymentObject passed in
                console.log("error", error);
              })
          });
      }
    });
    setTimeout(() => {

      this.loading.dismiss();
    }, 5000);
  }

Service page for placing an order after a successful transaction

placeOrder(orderDataObj){
  let headers = new HttpHeaders ({
    'Content-Type': 'application/x-www-form-urlencoded'
  });

  let orderData = this.JSON_to_URLEncoded(orderDataObj);

  this.apiUrl = `${this.siteUrl}${this.woocommercePath}orders?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
  console.log('API URL for order: ', this.apiUrl);

  return new Promise ((resolve) => {
    this.orderResp = this.http.post(this.apiUrl,orderData, {headers});
    this.orderResp.subscribe((responseData) => {
      resolve(responseData);
    });
  });

}

Few days back even i"m facing the same issue, technically when the ionic apk file running on the mobile/smartphone doesn't have any port number running on ie, http://localhost/dashboard instead of http://localhost:8100/dashboard.

So specify the redirect url as redirect_url: "http://localhost/home"

or to land back to same window/page where the payment started specify as redirect_url:window.location.href,

then you will be able to redirect back to the ionic app.

I think that you are doing it wrong; when the transaction succeeds the payment websites will notfiy you on a webhook URL this url should be on your server because they are a post requests. You cannot send a post request directly to your client (Browser/IONIC client) because they are not supposed to act as a web server. A simple solution would be to create an URL on your server that that receives the response and then redirect the user to your web app (Not sure if it is working with IONIC) in No:

http.post('/rave-callback',function(req,res){ 
// you can store the payment details in the db if you need to
   res.redirect('http://localhost:8100/home')
})

In your IONIC app you must change the redirect_url to redirect_url: "http://my-server-url.com/rave-callback

more infos about this here: https://medium.com/@jake_parkers/3d-secure-guidelines-9e17f9a6cf32

We don't have the full story so I mainly gussing, so I guess this is your problem:

if (event.url.indexOf('http://localhost:8100/home') != -1) {
  if (event.url.includes("payment_successfull")) {
  }
}

How do you know the payment gateway will redirect to http://localhost:8100/home ? It will not work becuase this is just YOUR local serv. If you configured it in the payment gateway provider you need to change that.

Your best bet (what I did) is to leave it at whatever defulat success page it already has, this page should have some keyword that you can use this function to check event.url.includes("your keyword here")

Or if you have to fill-in a value use their page and just add a parameter at the end with your keyword: www.url.com?status=payment_successfull

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM