要在Angular中保存Stripe订阅的付款详细信息并创建订阅,可以使用Stripe的JavaScript客户端库和Angular的HttpClient库。下面是一个示例解决方案:
npm install @stripe/stripe-js
npm install @angular/common/http
// environments/environment.ts
export const environment = {
production: false,
stripePublicKey: 'your_stripe_public_key'
};
// stripe.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class StripeService {
private stripe: any;
constructor(private http: HttpClient) {
this.loadStripe();
}
private async loadStripe() {
const stripe = await import('@stripe/stripe-js');
this.stripe = await stripe.loadStripe(environment.stripePublicKey);
}
createSubscription(paymentMethodId: string): Promise {
return this.http.post('/api/create-subscription', { paymentMethodId }).toPromise();
}
attachPaymentMethod(paymentMethodId: string): Promise {
return this.http.post('/api/attach-payment-method', { paymentMethodId }).toPromise();
}
getStripe(): any {
return this.stripe;
}
}
// component.ts
import { Component } from '@angular/core';
import { StripeService } from './stripe.service';
@Component({
selector: 'app-root',
template: `
`,
})
export class AppComponent {
constructor(private stripeService: StripeService) {}
async createSubscription() {
const stripe = this.stripeService.getStripe();
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: 'card',
card: {
number: '4242424242424242',
exp_month: 12,
exp_year: 2023,
cvc: '123'
}
});
if (error) {
console.error(error);
return;
}
try {
const result = await this.stripeService.createSubscription(paymentMethod.id);
console.log(result);
} catch (error) {
console.error(error);
}
}
async attachPaymentMethod() {
const stripe = this.stripeService.getStripe();
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: 'card',
card: {
number: '4242424242424242',
exp_month: 12,
exp_year: 2023,
cvc: '123'
}
});
if (error) {
console.error(error);
return;
}
try {
const result = await this.stripeService.attachPaymentMethod(paymentMethod.id);
console.log(result);
} catch (error) {
console.error(error);
}
}
}
请确保替换your_stripe_public_key
为您自己的Stripe公钥,并根据您的项目结构和后端API进行相应的调整。
这是一个基本的示例,您可以根据您的需求进行修改和扩展。