如何在Vue 3脚本设置中创建贝宝按钮?

zpgglvta  于 2023-01-09  发布在  Vue.js
关注(0)|答案(2)|浏览(271)

paypal developer docs显示了如何在Vue.js中实现Paypal按钮,但我不理解代码。在这一点上,我甚至不确定这是vue 2vue 3angular??代码。
1:在parent blade中导入脚本:

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"></script>

2:在组件的script tag中使用按钮?

paypal.Buttons.driver("vue", window.Vue);

3:这是我迷路的地方,在app.js中使用这个??:

@ng.core.Component({
  selector: 'my-app',
  template:
    <div id="app">
        <paypal-buttons [props]="{
            createOrder: createOrder,
            onApprove: onApprove
        }"></paypal-buttons>
    </div>
  ,
})
class AppComponent {
    createOrder(data, actions) {
      return actions.order.create({
          purchase_units: [{
              amount: {
                  value: '0.01'
              }
          }]
      });
    }
    onApprove(data, actions) {
      return actions.order.capture();
    }
}
@ng.core.NgModule({
    imports: [
        ng.platformBrowser.BrowserModule,
        paypal.Buttons.driver('angular2', ng.core)
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [
        AppComponent
    ]
})
class AppModule {}
ng.platformBrowserDynamic
    .platformBrowserDynamic()
    .bootstrapModule(AppModule);

会不会这甚至不是vue code,而是angular code
4:并将其放入vue component??:

<div id="container">
  <app></app>
</div>
<script>
  const PayPalButton = paypal.Buttons.driver("vue", window.Vue);

  Vue.component("app", {
    // The style prop for the PayPal button should be passed in as `style-object` or `styleObject` to avoid conflict with Vue's `style` reserved prop.
    template: `
      <paypal-buttons :on-approve="onApprove" :create-order="createOrder" :on-shipping-change="onShippingChange" :on-error="onError" :style-object="style" />
    `,
    components: {
      "paypal-buttons": PayPalButton,
    },

    computed: {
      createOrder: function () {
        return (data, actions) => {
          return actions.order.create({
            purchase_units: [
              {
                amount: {
                  value: "10",
                },
              },
            ],
          });
        }
      },
      onApprove: function () {
        return (data, actions) => {
          return actions.order.capture();
        }
      },
      onShippingChange: function () {
        return (data, actions) => {
          if (data.shipping_address.country_code !== 'US') {
            return actions.reject();
          }
          return actions.resolve();
        }
      },
      onError: function () {
        return (err) => {
          console.error(err);
          window.location.href = "/your-error-page-here";
        }
      },
      style: function () {
        return {
          shape: 'pill',
          color: 'gold',
          layout: 'horizontal',
          label: 'paypal',
          tagline: false
        }
      },
    },
  });

  const vm = new Vue({
    el: "#container",
  });
</script>

我的问题是,如何在Vue3的script setup中创建一个简单的贝宝按钮?paypal cdn是在父blade file中导入的。
例如:

<script setup>
import {onMounted} from "vue";

onMounted(() => {
    //create component from -> paypal.Buttons.driver("vue", window.Vue);
})
</script>

<template>
  <div id="checkout" class="checkout">
    <paypal-buttons></paypal-buttons>
  </div>
</template>
3gtaxfhh

3gtaxfhh1#

我建议采取以下实施方式:

  • 安装官方贝宝js npm软件包:第一个月

然后,您可以编写PaypalButtons组件,如下所示:

<script setup>
import {Inertia} from '@inertiajs/inertia';
import {loadScript} from '@paypal/paypal-js';
import {onMounted} from 'vue';

const props = defineProps({
    // Some kind of reference if you like
    reference: Object
});

onMounted(async() => {
    try {
        const paypal = await loadScript({
            'client-id': <your-paypal-client-id>
        });

        await paypal.Buttons({
            createOrder: function() {
                function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            // e.g reference.price
                            value: '<your-price>',
                        },
                    }],
                });
            },
            onApprove: function(data) {
                return actions.order.capture().then(function(orderData) {
                    // Successful capture!
                    // e.g. Inertia.post(route('order.update', reference.orderId)
                });
            },
            style: {
                // Adapt to your needs
                layout: 'vertical',
                color: 'gold',
                shape: 'rect',
                label: 'paypal',
            },
            // The following is optional and you can
            // limit the buttons to those you want to
            // provide
            fundingSource: paypal.FUNDING.PAYPAL,
        }).render('#paypal-button-container');
    } catch (error) {
        // Add proper error handling
        console.error(error);
    }
});
</script>

<template>
    <div id="paypal-button-container"></div>
</template>

现在将其用作:

<PaypalButtons :reference="reference" />
avwztpqn

avwztpqn2#

Paypal文档是一个巨大的混乱。服务器集成似乎是这样工作的:
如果您使用laravel作为后端,请将此文件导入app.blade.php/welcome.blade.php文件:

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"></script>

那么vue component就可以像这样:

<script setup>
import {onMounted} from "vue";

onMounted(() => {
    paypal.Buttons({

        // Call your server to set up the transaction
        createOrder: function(data, actions) {
            return fetch('/demo/checkout/api/paypal/order/create/', {
                method: 'post'
            }).then(function(res) {
                return res.json();
            }).then(function(orderData) {
                return orderData.id;
            });
        },

        // Call your server to finalize the transaction
        onApprove: function(data, actions) {
            return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
                method: 'post'
            }).then(function(res) {
                return res.json();
            }).then(function(orderData) {
                // Three cases to handle:
                //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                //   (2) Other non-recoverable errors -> Show a failure message
                //   (3) Successful transaction -> Show confirmation or thank you

                // This example reads a v2/checkout/orders capture response, propagated from the server
                // You could use a different API or structure for your 'orderData'
                var errorDetail = Array.isArray(orderData.details) && orderData.details[0];

                if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                    return actions.restart(); // Recoverable state, per:
                    // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
                }

                if (errorDetail) {
                    var msg = 'Sorry, your transaction could not be processed.';
                    if (errorDetail.description) msg += '\n\n' + errorDetail.description;
                    if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
                    return alert(msg); // Show a failure message (try to avoid alerts in production environments)
                }

                // Successful capture! For demo purposes:
                console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                var transaction = orderData.purchase_units[0].payments.captures[0];
                alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');

                // Replace the above to show a success message within this page, e.g.
                // const element = document.getElementById('paypal-button-container');
                // element.innerHTML = '';
                // element.innerHTML = '<h3>Thank you for your payment!</h3>';
                // Or go to another URL:  actions.redirect('thank_you.html');
            });
        }

    }).render('#paypal-button-container');
})

</script>

<template>
  <div id="checkout" class="checkout">
    <div id="paypal-button-container"></div>
  </div>
</template>

显示的付款方式是自动确定的,取决于您的IP(???)。您可以通过操作script import隐藏付款方式,如下所示:

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&disable-funding=card,giropay,sepa,sofort"></script>

相关问题