import { Injectable } from '@angular/core' ; import { environment } from '../../environments/environment' ; import { switchMap , map } from 'rxjs/operators' ; import { fromPromise } from 'rxjs/observable/fromPromise' ; import { Observable } from 'rxjs/Observable' ; import { HttpClient } from '@angular/common/http' ; import { Customer , Source , Charge , SubscriptionPlan , StripeObject } from './models' ; @ Injectable ( ) export class PaymentService { readonly api = `${ environment . functionsURL }/app` ; private stripe = Stripe ( environment . stripePublishable ) ; elements : any ; constructor ( private http ) { this . elements = this . stripe . elements ( ) ; } getCustomer ( ) { const url = `${ this . api }/customer/` ; return this . http . get < Customer > ( url ) ; } getCharges ( ) { const url = `${ this . api }/charges/` ; return this . http . get < StripeObject > ( url ) . map ( res => res . data ) ; } createCharge ( card , amount ) { const url = `${ this . api }/charges/` ; return fromPromise < Source > ( this . stripe . createSource ( card ) ) . pipe ( switchMap ( data => { return this . http . post < Charge > ( url , { amount , sourceId : data . source . id } ) ; } ) ) ; } attachSource ( card ) { const url = `${ this . api }/sources/` ; return fromPromise < Source > ( this . stripe . createSource ( card ) ) . pipe ( switchMap ( data => { return this . http . post < Source > ( url , { sourceId : data . source . id } ) ; } ) ) ; } attachSubscription ( sourceId , planId ) { const url = `${ this . api }/subscriptions` ; return this . http . post < SubscriptionPlan > ( url , { sourceId , planId } ) ; } cancelSubscription ( planId ) { const url = `${ this . api }/subscriptions/cancel` ; return this . http . put < SubscriptionPlan > ( url , { planId } ) ; } }