我正在尝试将PayPal按钮添加到现有的结帐页面中。但是,我遇到了很多麻烦,因为我们的项目使用Vue.js类组件,而我遇到的示例则不使用(官方的PayPal文档不使用类组件:https://developer.paypal.com/docs/business/checkout/configure-payments/single-page-app/)。
我遇到了使用mounted()钩子将PayPal SDK脚本注入DOM的解决方法,并且成功地使按钮出现,但存在的问题是,我无法使支付细节动态(订单信息,如总量、项目描述等存储在Vue组件的状态中,而且我还没有找到将该状态传递给DOM中的静态JS脚本的方法)。
目前,我正在尝试调整正式的PayPal文档以处理类组件,我的代码如下(与非PayPal相关的部分除外):
Index.html:
<!DOCTYPE html>
<html class="no-js" lang="en" dir="ltr">
<head>
<script defer src="https://www.paypal.com/sdk/js?client-id=abc123&disable-funding=credit,card"></script>
</head>
<body>
<div id="app">
<!-- The shop component is put inside here -->
</div>
</body>
</html>shop.vue:
<template>
<paypal-buttons :on-approve="onApprove" :create-order="createOrder" />
</template>
<script lang="ts" src="./shop.component.ts"></script>shop.component.ts:
const PayPalButton = paypal.Buttons.driver("vue", window.Vue);
@Component({
components: {
PayPalButton,
},
})
export default class Shop extends Vue {
public total = '10.0'; // Will be dynamic
public mounted(): void {
...
}
public createOrder(data, actions) {
return actions.order.create({
purchase_units : [{
amount: {
value: total
}
}]
});
}
public onApprove(data, actions) {
return actions.order.capture().then(function (details) {
console.log(details)
})
}
}此代码将成功构建,但由于出现错误,我无法实际打开该页。在浏览器控制台中,我看到以下错误:
TypeError:无法读取未定义的属性“组件”
在进一步调试时,我发现行paypal.Buttons.driver("vue", window.Vue);会导致错误,这是因为paypal未定义。我相当肯定,PayPal脚本在index.html中加载正确,我也不认为这是由于缺少npm包或导入。我在网上找到的为数不多的资源之一是:Vue PayPal implementation with vue-head, paypal not defined
不幸的是,这个链接的解决方案使用了mounted()钩子,这是我以前尝试过的,它没有解决提供我想要的动态总计的问题。
有人有使用PayPal SDK和Vue.js类组件的经验吗?任何帮助都将不胜感激!
发布于 2021-07-28 17:58:02
经过更多的测试后,我得出了这样的结论:很显然,可以将动态顺序发送到PayPal,即使您使用mounted()钩子将SDK脚本注入DOM。结果是,当我第一次尝试这样做时,我对Vue类组件有一个错误的理解,因此错误地引用了组件状态。
在我的最后代码中,我从PayPal中取出了<script>标记。我从其他2个文件中的代码修改如下:
shop.vue:
<template>
<div id="paypal-button"></div>
</template>
<script lang="ts" src="./shop.component.ts"></script>shop.component.ts:
export default class Shop extends Vue {
public total = '10.0'; // Will be dynamic
public mounted(): void {
const script = document.createElement('script');
const clientId = 'abc123';
script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}&disable-funding=credit,card`;
script.addEventListener('load', this.paypalSetLoaded);
document.body.appendChild(script);
}
public paypalSetLoaded() {
window.paypal
.Buttons({
style: {
color: 'blue',
shape: 'pill',
},
createOrder: this.paypalCreateOrder,
onApprove: this.paypalOnApprove,
})
.render('#paypal-button');
}
public paypalCreateOrder(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
currency_code: 'USD',
value: this.total,
}
}],
});
}
public paypalOnApprove(data, actions) {
return actions.order.capture().then(details => {
console.log(details);
});
}
}即使在程序执行过程中(由于用户交互) total的值发生了变化,仍然会向PayPal发送正确金额的订单。
我不确定这是否是最佳实践,但根据我所能看到的,代码可以工作,而且是高效的和可伸缩的。希望这能帮助其他遇到类似问题的人。
https://stackoverflow.com/questions/68492605
复制相似问题