使用FireStore云功能对课程进行条带化付款

时间:2019-11-13 06:03:41

标签: node.js angular firebase firebase-realtime-database stripe-payments

因此,我创建了一个页面,学生可以在其中选择想要注册的课程后重定向到该页面,然后在该页面上,学生将提供其个人信息,然后单击“继续注册”按钮。将打开一个条带化结帐表格,该表格将向他们收取该特定课程的费用,然后这些学生才能在Cloud Firestor数据库集合中注册。因此,我从这些教程link开始学习。但是我的云函数是用NodeJS后端编写的,因此我寻找了一些用于支付的示例条带化api,并在此github repo上找到了这些示例api。

我不确定如何使用这些API或这些API是否适合我,因为我的其他功能与这些Stripe功能略有不同。 非常感谢您的帮助,以了解如何实现此功能。我也在这里粘贴条纹功能。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const logging = require('@google-cloud/logging')();
const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';

// [START chargecustomer]
// Charge the Stripe customer whenever an amount is created in Cloud Firestore
exports.createStripeCharge = functions.firestore.document('stripe_customers/{userId}/charges/{id}').onCreate(async (snap, context) => {
      const val = snap.data();
      try {
        // Look up the Stripe customer id written in createStripeCustomer
        const snapshot = await admin.firestore().collection(`stripe_customers`).doc(context.params.userId).get()
        const snapval = snapshot.data();
        const customer = snapval.customer_id
        // Create a charge using the pushId as the idempotency key
        // protecting against double charges
        const amount = val.amount;
        const idempotencyKey = context.params.id;
        const charge = {amount, currency, customer};
        if (val.source !== null) {
          charge.source = val.source;
        }
        const response = await stripe.charges.create(charge, {idempotency_key: idempotencyKey});
        // If the result is successful, write it back to the database
        return snap.ref.set(response, { merge: true });
      } catch(error) {
        // We want to capture errors and render them in a user-friendly way, while
        // still logging an exception with StackDriver
        console.log(error);
        await snap.ref.set({error: userFacingMessage(error)}, { merge: true });
        return reportError(error, {user: context.params.userId});
      }
    });
// [END chargecustomer]]

// When a user is created, register them with Stripe
exports.createStripeCustomer = functions.auth.user().onCreate(async (user) => {
  const customer = await stripe.customers.create({email: user.email});
  return admin.firestore().collection('stripe_customers').doc(user.uid).set({customer_id: customer.id});
});

// Add a payment source (card) for a user by writing a stripe payment source token to Cloud Firestore
exports.addPaymentSource = functions.firestore.document('/stripe_customers/{userId}/tokens/{pushId}').onCreate(async (snap, context) => {
  const source = snap.data();
  const token = source.token;
  if (source === null){
    return null;
  }

  try {
    const snapshot = await admin.firestore().collection('stripe_customers').doc(context.params.userId).get();
    const customer =  snapshot.data().customer_id;
    const response = await stripe.customers.createSource(customer, {source: token});
    return admin.firestore().collection('stripe_customers').doc(context.params.userId).collection("sources").doc(response.fingerprint).set(response, {merge: true});
  } catch (error) {
    await snap.ref.set({'error':userFacingMessage(error)},{merge:true});
    return reportError(error, {user: context.params.userId});
  }
});

// When a user deletes their account, clean up after them
exports.cleanupUser = functions.auth.user().onDelete(async (user) => {
  const snapshot = await admin.firestore().collection('stripe_customers').doc(user.uid).get();
  const customer = snapshot.data();
  await stripe.customers.del(customer.customer_id);
  return admin.firestore().collection('stripe_customers').doc(user.uid).delete();
});

角度测试组件(不确定)

import * as firebase from 'firebase';

import { Component, Input, OnInit, ViewChild } from '@angular/core';

import { AngularFireFunctions } from '@angular/fire/functions';
import { PaymentService } from './payment.service';
import { environment } from '../../../../environments/environment';

@Component({
  selector: 'ngx-payment-request',
  templateUrl: './payment-request.component.html',
  styleUrls: ['./payment-request.component.scss'],
  providers: [PaymentService]
})
export class PaymentRequestComponent implements OnInit {

  // @Input() amount: 100;
  // @Input() label: 'Course';

  elements: any;
  paymentRequest: any;
  prButton: any;
  handler: any;
  amount: number = 500;
  confirmation: any;
  loading = false;

  @ViewChild('payElement', { static: true }) payElement;

  constructor(private pmt: PaymentService, private functions: AngularFireFunctions) { }

  ngOnInit() {
    // this.loadStripe();
    // this.pmt.showId();
    this.pmt.showId();
    this.handler = StripeCheckout.configure({
      // key: environment.stripeKey,
      image: 'https://oc1.ocstatic.com/images/logo_small.png',
      locale: 'auto',
      token: token => {
        this.pmt.processPayment(token, this.amount)
      },
      source:  async (source) => {
        this.loading = true;
        const user = this.pmt.showId();
        firebase.functions().useFunctionsEmulator('hxxxxxx.net')
        const fun = this.functions.httpsCallable('stripeCreateCharge');
        this.confirmation = await fun({ source: source.id, amount: this.amount}).toPromise();
        this.loading = false;
      }
    });
  }

  handlePayment(e) {
    const user = this.pmt.showId();
    this.handler.open({
      name: 'FireStarter',
      description: 'Pay your Dues',
      amount : this.amount,
    });
    e.preventDefault();
  }
 }

0 个答案:

没有答案
相关问题