我正在我的 Angular 项目中实施 PayPal 的智能支付按钮。我知道在我的 index.html 文件中我有以下脚本:
<script
src="https://www.paypal.com/sdk/js?client-id=MY_CLIENT_ID">
</script>
Run Code Online (Sandbox Code Playgroud)
我正在尝试实现类似 Cart 的系统,因此将有多个 Client-Id,具体取决于哪个企业正在使用它。因此,我意识到我需要将 动态设置MY_CLIENT_ID为使用该站点的企业帐户的 Client-Id。但我能找到的只是在index.html. 当我创建订单以在我的 Angular 组件中设置客户端 ID 时,我需要某种方式。类似于以下内容:
paypal.Buttons({
clientId: dataService.business.clientId // **IMPORTANT** PART I NEED TO DYNAMICALLY SET THE CLIENTID
// THE REST IS JUST TYPICAL PAYPAL BUTTON STUFF.
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [
{
description: this.product.description,
amount: {
currency_code: 'USD',
value: this.product.price,
}
}
]
});
},
onApprove: async (data, actions) => {
const order = await actions.order.capture();
this.paidFor = true;
console.log(order);
}
})
.render(this.paypalElement.nativeElement);
Run Code Online (Sandbox Code Playgroud)
我不相信商家 ID 是我正在寻找的,因为我知道企业的客户 ID,我只是无法将其硬编码,但我不确定。谢谢你的帮助。
我会创建一个PayPalService这样的并从组件中调用它。
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';
import { fromEvent, Observable } from 'rxjs';
import { first } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PaypalService {
constructor(
@Inject(DOCUMENT)
private document: Document
) {}
public initiate(clientId: string): Observable<void> {
const paypalScriptElement: HTMLScriptElement = this.document.createElement('script');
paypalScriptElement.src = `https://www.paypal.com/sdk/js?client-id=${clientId}`;
paypalScriptElement.id = 'paypal-script';
this.document.head.appendChild(paypalScriptElement);
return fromEvent<void>(paypalScriptElement, 'load').pipe(first());
}
public remove(): void {
const paypalScriptElement = this.document.getElementById('paypal-script');
this.document.head.removeChild(paypalScriptElement);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的组件中,使用如下:
this.paypalService.initiate(dataService.business.clientId).subscribe(
() => paypal.Buttons({
// THE REST IS JUST TYPICAL PAYPAL BUTTON STUFF.
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [
{
description: this.product.description,
amount: {
currency_code: 'USD',
value: this.product.price,
}
}
]
});
},
onApprove: async (data, actions) => {
const order = await actions.order.capture();
this.paidFor = true;
console.log(order);
}
}).render(this.paypalElement.nativeElement)
);
Run Code Online (Sandbox Code Playgroud)
请确保调用this.paypalService.remove()在ngOnDestroy您的组件中。
此外,请确保从中删除任何硬编码的 PayPal 脚本标签,index.html因为现在将以编程方式添加它。
| 归档时间: |
|
| 查看次数: |
711 次 |
| 最近记录: |