集成 Stripe 元素和 Vue.js 以设置自定义付款表单

Stripe 是处理在线支付的最佳方法之一,最近他们发布了 Stripe Elements。 Stripe Elements是他们预先构建的用户界面组件库,可以帮助您轻松创建自己的支出流程。

在本文中,我将向您展示如何集成 Vue.js 和 Stripe Elements,以便您可以在您的网站或应用程序中快速设置自定义的卡付款表格。

<$>[注] 查看 此帖子 如果您有兴趣将 Stipe Elements 集成到 Angular 应用程序中。

什么是 Stripe 元素

Stripe Elements 是一组组件,具有各种元素,您可以用来创建支票表格,如按钮和输入来收集用户的信息。我们将在本文中专注于 card 元素。 卡片元素允许您在一个元素中收集卡片信息。

安装

Stripe Elements 是 Stripe.js 的一部分,所以您只需要在您的页面中包含下面的脚本标签, Stripe 建议始终将其直接包含在您的 index.html 页面上,使用以下 URL:

1<script src="https://js.stripe.com/v3/"></script>

初始化卡片元素

Stripe Elements 处理并初始化自己的 UI,因此如果 Vue.js 在 Stripe Elements 之前初始化,可能会出现冲突。

 1<template>
 2  <div ref="card"></div>
 3</template>
 4
 5<script>
 6let stripe = Stripe(`YOUR_STRIPE_PUBLISHABLE_KEY`),
 7    elements = stripe.elements(),
 8    card = undefined;
 9
10export default {
11  mounted: function () {
12    card = elements.create('card');
13    card.mount(this.$refs.card);
14  }
15};
16</script>

定制卡片元素的风格

要定制元素的风格,您必须声明对象内部的风格:

 1let style = {
 2  base: {
 3    border: '1px solid #D8D8D8',
 4    borderRadius: '4px',
 5    color: "#000",
 6  },
 7
 8  invalid: {
 9    // All of the error styles go inside of here.
10  }
11
12};

然后,当您初始化卡元素时,您可以将该对象传入创建方法,从而确保您声明的样式应用于该元素。

1card = elements.create('card', style);

收集 Stripe 代币

Stripe 允许您收集并将 Elements 收集的卡片信息转换为一次性代币,然后将其传输到您的服务器中以便在 API 调用中使用。

您可以将购买方法绑定到一个按钮,然后在该方法内部调用stripe.createToken方法。

 1<template>
 2  <div ref="card"></div>
 3  <button v-on:click="purchase">Purchase</button>
 4</template>
 5
 6<script>
 7let stripe = Stripe(`YOUR_STRIPE_PUBLISHABLE_KEY`),
 8    elements = stripe.elements(),
 9    card = undefined;
10
11export default {
12  mounted: function () {
13    card = elements.create('card');
14    card.mount(this.$refs.card);
15  },
16
17  purchase: function () {
18    stripe.createToken(card).then(function(result) {
19      // Access the token with result.token
20    });
21  }
22};
23</script>

卡片的错误

卡片元素会自动捕捉与卡片号码不符合Visa、MasterCard和其他支持的卡片类型的语法的错误,尽管如此,有时不同类型的错误可以通过,并且Stripe Elements允许您在createToken方法中使用result.error变量来处理。

 1purchase: function () {
 2
 3  let self = this;
 4
 5  stripe.createToken(card).then(function(result) {
 6    if (result.error) {
 7      self.hasCardErrors = true;
 8      self.$forceUpdate(); // Forcing the DOM to update so the Stripe Element can update.
 9      return;
10    }
11
12  });
13}

参考

Stripe Elements 是 Stripe 的解决方案,可以快速轻松地处理付款,并且很容易集成到 Vue.js 项目中。

Published At
Categories with 技术
Tagged with
comments powered by Disqus