Узнайте, как интегрировать платежный шлюз Stripe в Angular 17, с помощью этого пошагового руководства. Библиотека Ngx Stripe упрощает создание безопасных и масштабируемых платежных решений.
Шаг для платежного шлюза Stripe в Angular 17
Без лишних слов, давайте посмотрим на приведенный ниже пример кода:
Шаг 1. Создайте проект Angular 17
Вы можете легко создать свое угловое приложение, используя следующую команду:
ng new my-new-app
Шаг 2. Создайте приложение Stripe
Здесь вам нужно создать ключ API полосы. Итак, давайте перейдем к Перейти к учетной записи Stripe.
Зарегистрируйтесь, чтобы создать учетную запись разработчика Stripe.
Нажмите на раздел «Получите тестовые ключи API».
Вы найдете ключ API, как показано ниже. Этот ключ API нам нужно использовать в нашем коде:
pk_test_09GJJuNx4ScHIcoML69tx2aa
Шаг 3. Обновите файл TS компонента.
Здесь мы будем использовать Stripe API. Итак, давайте обновим "app.comComponent.ts" файл.
src/app/app.comComponent.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
paymentHandler: any = null;
stripeAPIKey: any = 'YOUR_STRIPE_KEY';
constructor() {}
/*------------------------------------------
--------------------------------------------
ngOnInit() Function
--------------------------------------------
--------------------------------------------*/
ngOnInit() {
this.invokeStripe();
}
/*------------------------------------------
--------------------------------------------
makePayment() Function
--------------------------------------------
--------------------------------------------*/
makePayment(amount: any) {
const paymentHandler = (<any>window).StripeCheckout.configure({
key: this.stripeAPIKey,
locale: 'auto',
token: function (stripeToken: any) {
console.log(stripeToken);
alert('Stripe token generated!');
},
});
paymentHandler.open({
name: 'ItSolutionStuff.com',
description: '3 widgets',
amount: amount * 100,
});
}
/*------------------------------------------
--------------------------------------------
invokeStripe() Function
--------------------------------------------
--------------------------------------------*/
invokeStripe() {
if (!window.document.getElementById('stripe-script')) {
const script = window.document.createElement('script');
script.id = 'stripe-script';
script.type = 'text/javascript';
script.src = 'https://checkout.stripe.com/checkout.js';
script.onload = () => {
this.paymentHandler = (<any>window).StripeCheckout.configure({
key: this.stripeAPIKey,
locale: 'auto',
token: function (stripeToken: any) {
console.log(stripeToken);
alert('Payment has been successfull!');
},
});
};
window.document.body.appendChild(script);
}
}
}
Шаг 4. Обновите HTML-файл компонента.
Давайте обновим файл app.comComponent.html следующим кодом:
src/app/app.comComponent.html
<div class="container">
<h2 class="mt-5 mb-4">Angular 17 Stripe Payment Gateway Example</h2>
<div class="col-md-5 mb-2">
<button (click)="makePayment(15)" class="btn btn-danger btn-block">Pay $15</button>
</div>
<div class="col-md-5 mb-2">
<button (click)="makePayment(25)" class="btn btn-primary btn-block">Pay $25</button>
</div>
<div class="col-md-5">
<button (click)="makePayment(35)" class="btn btn-success btn-block">Pay $35</button>
</div>
</div>
Запустите приложение Angular:
Все необходимые шаги выполнены, теперь вам нужно ввести приведенную ниже команду и нажать Enter, чтобы запустить приложение Angular:
ng serve
Теперь перейдите в веб-браузер, введите указанный URL-адрес и просмотрите выходные данные приложения:
http://localhost:4200