cordova-plugin-purchase 을 연동한 capacitor 결제 연동
결제 시스템 달기
이전에는 @ionic-native/in-app-purchase-2 와 cordova-plugin-purchase 의 최신 버젼과 호환이 되지 않아 cordova-plugin-purchase v 11.x.x 를 사용하였다.
하지만 Play 결제 라이브러리 v4 가 지원중단됨에 따라 최근 버젼( PBL 버전 5 이상)으로 변경해야 함으로 cordova-plugin-purchase 의 최신 버젼을 통한 직접 연결을 시도하여보았습니다.
아래는 간단한 소스와 예제입니다.
참조 : https://github.com/j3k0/cordova-plugin-purchase/blob/master/src/example/example.ts
install
"cordova-plugin-purchase": "^13.8.6",
npm i cordova-plugin-purchase
예제
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Platform } from '@ionic/angular';
import 'cordova-plugin-purchase';
..........
export class SamplePage implements OnInit {
private ordered = false;
private store!: CdvPurchase.Store;
constructor(
private plt: Platform,
private ref: ChangeDetectorRef,
) {
this.store = CdvPurchase.store;
this.store.error( (error) => {
console.log('ERROR ' + error.code + ': ' + error.message);
});
this.store.ready( () => {
console.log('CdvPurchase is ready');
});
}
ngOnInit() {
this.registerAbo();
}
private registerAbo() {
const { ProductType, Platform } = CdvPurchase;
// for the backend, we send the userId with this method
this.store.applicationUsername = () => "USER_ID";
// this.store.validator = "MY_CUSTOM_APPLE_VALIDATOR_URL";
this.store.verbosity = 4;
this.store.register([{
id: 'ProductId1',
type: ProductType.CONSUMABLE,
platform: Platform.GOOGLE_PLAY,
},
..........
{
id: 'ProductId1',
type: ProductType.CONSUMABLE,
platform: Platform.APPLE_APPSTORE,
}
]);
if(this.store.isReady) {
this.updateStore();
} else {
if (this.plt.is('ios')) { // init apple
this.store.initialize([{ platform: Platform.APPLE_APPSTORE }]);
} else if (this.plt.is('android')) { // init google
this.store.initialize([{ platform: Platform.GOOGLE_PLAY }]);
} else {// not mobile
this.store.initialize([{platform: Platform.TEST}])
}
}
this.store.when()
.productUpdated(product => { // store.register 시 이 부분이 trigger 된다.
this.ref.detectChanges();
})
.approved(transaction => {
const monitor = this.store.monitor(transaction, state => {
if(state === 'approved') {
}
if (state === 'finished') {
monitor.stop();
}
})
transaction.verify().then(() => {
})
})
.pending(transaction => {
})
.verified(receipt => {
receipt.finish().then(() => {
this.ref.detectChanges();
})
})
.unverified(receipt => {
if(receipt.payload.ok === false) {
}
})
.receiptUpdated((receipt) => {
this.ref.detectChanges();
})
} // registerAbo() {
async updateStore() {
this.store.update().then(() => {
console.log('store update done')
});
}
public payment(id: string) { // html에서 call하는 부분으로 id는 product 아이디를 string으로 받아서 현재 poducts중에 찾아 offers를 가져오는 방식을 취했다.
const product = _.find(this.store.products, (product) =>{
return product.id === id;
});
if (product) {
this.ordered = true;
this.store.order(product.offers[0]);
} else {
console.log('결제 상품이 존재 하지 않습니다.');
};
}
}