Jump to content

Recommended Posts

Olá galera, Boa tarde!

Estou com um probleminha em Ionic que está quebrando muito minha cabeça por dias.

Método de pagamento do paypal aparece em meu site, mas não aparece no app ionic, o que será? Já tentei de tudo. Esse app faz comunicação via API do Woocommerce, e lá está habilitado a forma de pagamento com PayPal, porém só não aparece no app, já que na página de checkout no meu site, aparece.

 

Segue o código da página de checkout do app:

 

import { Component, Inject } from '@angular/core';
import { NavController, NavParams, AlertController, Loading, LoadingController, ToastController, App } from 'ionic-angular';
import { PlacedPage } from '../placed/placed';
import { PaymentGateway } from "../../models/payment-gateway.models";
import { Constants } from "../../models/constants.models";

import { WordpressClient } from '../../providers/wordpress-client.service';
import { Global } from '../../providers/global';
import { Subscription } from "rxjs/Subscription";
import { CartItem } from "../../models/cart-item.models";
import { OrderRequest } from "../../models/order-request.models";
import { Address } from "../../models/address.models";
import { ShippingLine } from "../../models/shipping-line.models";
import { UserResponse } from "../../models/user-response.models";
import { OrderResponse } from "../../models/order-response.models";
import { Currency } from "../../models/currency.models";
import { InAppBrowser, InAppBrowserOptions } from '@ionic-native/in-app-browser';
import { sha512 } from 'js-sha512';
import { APP_CONFIG, AppConfig } from '../../app/app.config';
import { OrderUpdateRequest } from '../../models/order-update-request.models';
import { Coupon } from '../../models/coupon.models';
import { HomePage } from '../home/home';
import { TranslateService } from '@ngx-translate/core';
import { Helper } from '../../models/helper.models';
import { ShippingMethod } from '../../models/shipping-method.models';
import { PayPal, PayPalPayment, PayPalConfiguration, PayPalPaymentDetails } from '@ionic-native/paypal';

@Component({
	selector: 'page-payment',
	templateUrl: 'payment.html',
	providers: [WordpressClient]
})

export class PaymentPage {
	private loading: Loading;
	private loadingShown: Boolean = false;
	private placedPagePushed: Boolean = false;
	private paymentDone: Boolean = false;
	private paymentFailAlerted: Boolean = false;

	private subscriptions: Array<Subscription> = [];
	private paymentGateways = new Array<PaymentGateway>();
	private cartItems: Array<CartItem>;
	private selectedPaymentGateway;
	private selectedAddress: Address;
	private orderRequest: OrderRequest;
	private orderId = -1;
	private user: UserResponse;
	private totalItems = 0;
	private total = 0;
	private couponApplied = false;
	private pickupTime = 0;
	private deliveryTime = 0;
	private shippingChargeGlobal: number;

	constructor(@Inject(APP_CONFIG) private config: AppConfig, public translate: TranslateService, private iab: InAppBrowser, private toastCtrl: ToastController, public navCtrl: NavController, private navParams: NavParams, private service: WordpressClient, private loadingCtrl: LoadingController, private alertCtrl: AlertController, public appCtrl: App) {
		this.cartItems = this.navParams.get('cart');
		this.totalItems = this.navParams.get('totalItems');
		this.total = this.navParams.get('total');
		this.shippingChargeGlobal = this.navParams.get('shippingChargeGlobal');

		let paymentGateways = JSON.parse(window.localStorage.getItem(Constants.PAYMENT_GATEWAYS));
		this.selectedAddress = JSON.parse(window.localStorage.getItem(Constants.SELECTED_ADDRESS));


		if (paymentGateways != null) {
			for (let pg of paymentGateways) {
				if (pg.enabled && this.paymentImplemented(pg.id)) {
					this.paymentGateways.push(pg);
				}
			}
		}
	}

	ionViewWillLeave() {
		this.subscriptions.forEach((subscription: Subscription) => {
			subscription.unsubscribe();
		});
		this.dismissLoading();
	}

	paymentImplemented(id) {
		return id === "pumcp" || id === "payuindia" || id === "cod";
	}

	paymentMethod(paymentGateway) {
		this.selectedPaymentGateway = paymentGateway;
	}

	placedPage() {
		if (this.selectedPaymentGateway == null) {
			this.translate.get('field_error_payment_method').subscribe(value => {
				this.showToast(value);
			});
		} else {
			this.orderRequest = new OrderRequest();
			this.orderRequest.payment_method = this.selectedPaymentGateway.id ? this.selectedPaymentGateway.id : "cod";
			this.orderRequest.payment_method_title = this.selectedPaymentGateway.title ? this.selectedPaymentGateway.title : "cod";
			this.orderRequest.set_paid = false;
			this.orderRequest.billing = this.selectedAddress;
			this.orderRequest.shipping = this.selectedAddress;
			this.user = JSON.parse(window.localStorage.getItem(Constants.USER_KEY));
			this.orderRequest.customer_id = String(this.user.id);

			let selectedShippingMethod: ShippingMethod = JSON.parse(window.localStorage.getItem(Constants.SELECTED_SHIPPING_METHOD));
			if (selectedShippingMethod) {
				let shippingTotal = 0;
				for (let ci of this.cartItems) {
					if (!ci.product.shipping_cost_use_global && ci.product.shipping_cost != 1)
						shippingTotal = shippingTotal + ci.product.shipping_cost;
				}
				if (this.shippingChargeGlobal != -1) {
					shippingTotal = shippingTotal + this.shippingChargeGlobal;
				}
				this.orderRequest.shipping_lines = new Array<ShippingLine>();
				this.orderRequest.shipping_lines.push(new ShippingLine(selectedShippingMethod.method_id, selectedShippingMethod.method_title, String(shippingTotal)));
			}

			this.orderRequest.line_items = this.cartItems;
			for (let item of this.orderRequest.line_items) {
				item.product = null;
			}

			this.translate.get('order_creating').subscribe(value => {
				this.presentLoading(value);
			});
			let coupon: Coupon = JSON.parse(window.localStorage.getItem(Constants.SELECTED_COUPON));
			let subscription: Subscription = this.service.createOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), this.orderRequest).subscribe(data => {
				this.orderId = data.id;
				if (coupon) {
					this.applyCoupon(coupon);
				} else {
					this.orderPlaced();
				}
			}, err => {
				console.log(err);
				this.dismissLoading();
				let orderId = Helper.extractOrderIdFromError(err);
				if (orderId != -1) {
					this.orderId = orderId;
					if (coupon) {
						this.applyCoupon(coupon);
					} else {
						this.orderPlaced();
					}
				} else {
					this.translate.get('order_failed').subscribe(value => {
						this.showToast(value);
					});
					this.appCtrl.getRootNav().setRoot(HomePage);
				}
			});
			this.subscriptions.push(subscription);
		}
	}

	applyCoupon(coupon) {
		let couponSubs: Subscription = this.service.applyCouponCode(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), coupon.code).subscribe(data => {
			this.couponApplied = true;
			window.localStorage.removeItem(Constants.SELECTED_COUPON);
			this.translate.get('confirm_order_coupon_applied').subscribe(value => {
				this.showToast(value);
			});
			this.orderPlaced();
		}, err => {
			console.log(err);
			this.dismissLoading();
		});
		this.subscriptions.push(couponSubs);
	}

	orderPlaced() {
		this.dismissLoading();
		if (this.selectedPaymentGateway.id && this.selectedPaymentGateway.id === "cod") {
			this.clearCart();
			this.navCtrl.setRoot(PlacedPage);
		} else if (this.selectedPaymentGateway.id === "pumcp" || this.selectedPaymentGateway.id === "payuindia") {
			this.initPayUMoney();
		} else {
			this.translate.get('order_placed_cod').subscribe(value => {
				this.showToast(value);
			});
			this.clearCart();
			this.navCtrl.setRoot(PlacedPage);
		}
	}

	initPayUMoney() {
		let name = this.user.first_name && this.user.first_name.length ? this.user.first_name : this.user.username;
		let mobile = this.user.username;
		let email = this.user.email;
		let bookingId = String(Math.floor(Math.random() * (99 - 10 + 1) + 10)) + this.orderId;
		let productinfo = this.orderId;
		let salt = this.config.payuSalt;
		let key = this.config.payuKey;
		let amt = this.couponApplied ? this.total : this.totalItems;
		let string = key + '|' + bookingId + '|' + amt + '|' + productinfo + '|' + name + '|' + email + '|||||||||||' + salt;
		let encrypttext = sha512(string);

		//let url = "payumoney/payuBiz.html?amt=" + amt + "&name=" + name + "&mobileNo=" + mobile + "&email=" + email + "&bookingId=" + bookingId + "&productinfo=" + productinfo + "&salt=" + salt + "&key=" + key;
		let url = "payumoney/payuBiz.html?amt=" + amt + "&name=" + name + "&mobileNo=" + mobile + "&email=" + email + "&bookingId=" + bookingId + "&productinfo=" + productinfo + "&hash=" + encrypttext + "&salt=" + salt + "&key=" + key;

		let options: InAppBrowserOptions = {
			location: 'yes',
			clearcache: 'yes',
			zoom: 'yes',
			toolbar: 'no',
			closebuttoncaption: 'back'
		};
		const browser: any = this.iab.create(url, '_blank', options);
		browser.on('loadstop').subscribe(event => {
			browser.executeScript({
				file: "payumoney/payumoneyPaymentGateway.js"
			});

			if (event.url == "http://localhost/success.php") {
				this.paymentSuccess();
				browser.close();
			}
			if (event.url == "http://localhost/failure.php") {
				this.paymentFailure();
				browser.close();
			}
		});
		browser.on('exit').subscribe(event => {
			if (!this.paymentDone && !this.paymentFailAlerted) {
				this.paymentFailure();
			}
		});
		browser.on('loaderror').subscribe(event => {
			this.showToast('something_went_wrong');
		});
	}

	paymentFailure() {
		this.paymentFailAlerted = true;
		let subscription: Subscription = this.service.updateOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), new OrderUpdateRequest('cancelled')).subscribe(data => {
		}, err => {
			console.log(err);
		});
		this.subscriptions.push(subscription);


		this.translate.get(['payment_fail_title', 'payment_fail_message', 'ok']).subscribe(res => {
			let alert = this.alertCtrl.create({
				title: res.payment_fail_title,
				message: res.payment_fail_message,
				buttons: [{
					text: res.ok,
					role: 'cancel',
					handler: () => {
						this.done();
						console.log('Okay clicked');
					}
				}]
			});
			alert.present();
		});
	}

	paymentSuccess() {
		this.paymentDone = true;
		this.clearCart();
		this.translate.get('just_a_moment').subscribe(value => {
			this.presentLoading(value);
		});
		let subscription: Subscription = this.service.updateOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), { set_paid: true }).subscribe(data => {
			this.done();
		}, err => {
			this.done();
			this.paymentSuccess();
			console.log(err);
		});
		this.subscriptions.push(subscription);
	}

	done() {
		if (!this.placedPagePushed) {
			this.placedPagePushed = true;
			this.dismissLoading();
			this.appCtrl.getRootNav().setRoot(this.paymentFailAlerted ? HomePage : PlacedPage);
		}
	}

	private presentLoading(message: string) {
		this.loading = this.loadingCtrl.create({
			content: message
		});

		this.loading.onDidDismiss(() => { });

		this.loading.present();
		this.loadingShown = true;
	}

	private dismissLoading() {
		if (this.loadingShown) {
			this.loadingShown = false;
			this.loading.dismiss();
		}
	}

	private presentErrorAlert(msg: string) {
		let alert = this.alertCtrl.create({
			title: 'Error',
			subTitle: msg,
			buttons: ['OK']
		});
		alert.present();
	}

	showToast(message: string) {
		let toast = this.toastCtrl.create({
			message: message,
			duration: 3000,
			position: 'bottom'
		});
		toast.onDidDismiss(() => {
			console.log('Dismissed toast');
		});
		toast.present();
	}

	clearCart() {
		let cartItems = new Array<CartItem>();
		window.localStorage.setItem('cartItems', JSON.stringify(cartItems));
	}
}

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By tony_lu
      Ola pessoal tudo bem? Gostaria de saber se existe a possibilidade de no meu site eu inserir um link para que o usuario ao clicar, crie um icone de atalho na area de trabalho do celular, tanto android quanto Apple, alguem sabe?
    • By jrxxjr
      Sou iniciante em Android, e fiz uma pequena aplicação Android de teste, usando Java, para aprender a utilizar um ListView com botões, e tive um problema. Os botões não funcionam direito, as vezes eu clico em cima do Edit, ele muda a mensagem para clicado, "Edit", confirmando que eu cliquei ai. Mas tem vezes que eu clico no botão Delete, e depois no botão Edit, e o texto não é mudado, ou seja o evento click não funcionou, se eu coloco um break point, no código-fonte, onde está entrando no evento setOnItemClickListener. Mas a mensagem exibida, não está correta.
      E tem um outro erro, de funcionamento do AlertDialog, da mensagem de confirmação de deleção.
      O código-fonte está abaixo.
      Por favor, alguém poderia me ajudar ?
       
      AgendaActivity.java
      package com.test.android.view; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.test.android.model.Agenda; import com.test.android.util.Util; public class AgendaActivity extends AppCompatActivity { ListView listview; MyArrayAdapter agendaArrayAdapter; ArrayList<AgendaTo> agendaArray = new ArrayList<AgendaTo>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_agenda); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Nick", 50))); agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("John", 50))); agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Anthony", 50))); agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("James", 50))); agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Jack", 50))); agendaArray.add(new AgendaTo(sdf.format(new Date()), Util.fillSpaces("Jeremy", 50))); agendaArray.add(new AgendaTo(sdf.format(new Date()),Util.fillSpaces("Long", 50))); agendaArrayAdapter = new MyArrayAdapter(AgendaActivity.this, R.layout.list_item, agendaArray); listview = (ListView) findViewById(R.id.listView); listview.setItemsCanFocus(false); listview.setAdapter(agendaArrayAdapter); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, final int position, long id) { Toast.makeText(AgendaActivity.this, "List Item Clicked:" + position, Toast.LENGTH_LONG) .show(); } }); } } MyArrayAdapter.java
      package com.test.android.view; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.ArrayList; public class MyArrayAdapter extends ArrayAdapter<AgendaTo> { Context context; int layoutResourceId; ArrayList<AgendaTo> agendas = new ArrayList<AgendaTo>(); public MyArrayAdapter(Context context, int layoutResourceId, ArrayList<AgendaTo> agendas) { super(context, layoutResourceId, agendas); this.layoutResourceId = layoutResourceId; this.context = context; this.agendas = agendas; } @Override public View getView(int position, View convertView, ViewGroup parent) { View item = convertView; AgendaWrapper agendaWrapper = null; if (item == null) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); item = inflater.inflate(layoutResourceId, parent, false); agendaWrapper = new AgendaWrapper(); agendaWrapper.nome = (TextView) item.findViewById(R.id.textNome); agendaWrapper.data = (TextView) item.findViewById(R.id.textData); agendaWrapper.edit = (Button) item.findViewById(R.id.btnEdit); agendaWrapper.delete = (Button) item.findViewById(R.id.btnDelete); item.setTag(agendaWrapper); } else { agendaWrapper = (AgendaWrapper) item.getTag(); } AgendaTo agenda = agendas.get(position); agendaWrapper.nome.setText(agenda.getNome()); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); agendaWrapper.data.setText(sdf.format(agenda.getData())); agendaWrapper.edit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "Edit", Toast.LENGTH_LONG).show(); } }); final int absolutePsition = position; final AgendaWrapper itemDelete = agendaWrapper; final ViewGroup viewGroup = parent; agendaWrapper.delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "Delete " + absolutePsition, Toast.LENGTH_LONG).show(); AlertDialog diaBox = AskOption(itemDelete, absolutePsition, viewGroup); diaBox.show(); } }); return item; } private AlertDialog AskOption(AgendaWrapper agendaWrapper, int position, final ViewGroup viewGroup) { final int deletePosition = position; AlertDialog myQuittingDialogBox = new AlertDialog.Builder(context) .setTitle("Delete") .setMessage("Do you want to Delete") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { agendas.remove(deletePosition); refreshListView(agendas, viewGroup); dialog.dismiss(); } private void refreshListView(final ArrayList<AgendaTo> agendas, final ViewGroup viewGroup) { final MyArrayAdapter myArrayAdapter = new MyArrayAdapter(context, R.layout.list_item, agendas); final LayoutInflater inflater = ((Activity) context).getLayoutInflater(); final View view = inflater.inflate(layoutResourceId, viewGroup, false); final ListView listview = (ListView) view.findViewById(R.id.listView); listview.setAdapter(myArrayAdapter); } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); return myQuittingDialogBox; } static class AgendaWrapper { TextView nome; TextView data; Button edit; Button delete; } } list_item.xml
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".AgendaActivity" > <TextView android:id="@+id/textNome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Nome:" android:width="50dp" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/textData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textData" android:layout_alignTop="@id/textNome" android:layout_alignRight="@id/textNome" android:layout_alignParentLeft="true" android:layout_marginTop="5dp" android:width="50dp" android:text="Data:" android:textAppearance="?android:attr/dateTextAppearance" android:textSize="16sp" /> <Button android:id="@+id/btnEdit" android:layout_width="80dp" android:layout_height="40dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:background="#99CC" android:focusable="false" android:focusableInTouchMode="false" android:text="Edit" android:textColor="#FFFFFF" /> <Button android:id="@+id/btnDelete" android:layout_width="80dp" android:layout_height="40dp" android:layout_alignParentRight="true" android:layout_below="@+id/btnEdit" android:layout_marginTop="3dp" android:background="#99CC" android:focusable="false" android:focusableInTouchMode="false" android:text="Delete" android:textColor="#FFFFFF" /> </RelativeLayout> activity_agenda.xml
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#990044" tools:context="com.test.android.view.AgendaActivity" > <TextView android:id="@+id/listLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:text="Touch List" android:textColor="#FFFFFF" android:textSize="25sp" /> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/listLabel" android:layout_marginTop="5dp" android:cacheColorHint="#FFFFFF" /> </RelativeLayout>  
    • By rockrgo
      Olá galera, tudo bem?
      Estou com um problema no upload de arquivo em uma webview, para ser mais específico só acontece na versãp 13.5 do iOS. Ao selecionar a imagem no Photo Library ocorre o seguinte erro.
      [assertion] Error acquiring assertion: <NSError: 0x600000e2fcf0; domain: RBSAssertionErrorDomain; code: 2; reason: "Client is missing required entitlement"> { userInfo = { RBSAssertionAttribute = <RBSLegacyAttribute: 0x7ff8776120e0; requestedReason: FinishTaskUnbounded; reason: FinishTaskUnbounded; flags: PreventTaskSuspend>; } } O upload ocorre, mas por este motivo a apple está reprovando o build.
    • By thekingowl
      Mala Vermelha
       
      Depois de quase dois anos de desenvolvimento, tive o prazer de ter meu jogo finalmente lançado na Play Store. Ele foi desenvolvido em uma plataforma para jogos browser, chamada Twine. Com algumas linhas de código em Java para adequar ao Mobile e convertido através do PhoneGap, consegui fazer a versão mobile para Android.
       
      Em "Mala Vermelha" você viverá a história da Policial Muriel. Entendiada na cidade pequena, Muriel tem sua vida alterada quando uma mala vermelha aparece na meio da cidade. É o início da aventura de Muriel, tentando capturar um assassino, antes que ele termine seu plano. Você tomará as decisões durante a investigação, levando Muriel aos mais diversos locais da cidade, em busca de pistas para desvendar o padrão do assassino. Enfrente não só o assassino, mas como os cidadãos da cidade.
       
      Totalmente em português, "Mala Vermelha" faz com que cada detalhe apresentado na história, possa ser utilizado para desvendar o enigma do assassino. Cada decisão a levará a um destino diferente. Com múltiplos finais, "Mala Vermelha" fará com que você escolha qual o melhor desfecho para o seu estilo de jogo. Não existe certo ou errado. Você decide.
       
      Mala Vermelha na Play Store: https://bit.ly/2XSfImx
      Blog: https://thekingowlgames.blogspot.com/2020/04/mala-vermelha_20.html
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.