LoginSignup
33
28

More than 5 years have passed since last update.

StripeをVueにシンプルに導入してみた

Last updated at Posted at 2019-03-08

はじめに

カード決済システムのStripeをVueに組み込んだので備忘録として最低限動くコードを載せておきます
cssはサボって設定してないのでお好きなようにやっちゃってくださいw
あとstripe_idは自分のに置き換えましょう

完成形

cssがないので見た目があれですが、機能としては問題ないです

image.png

実装

スクリプトを読み込む

1行追加するだけ。簡単。

index.html
  <head>
    <script src="https://js.stripe.com/v3/"></script>
  </head>

Vueの開発

こんな感じが最低限動く形かなと。

stripe.vue
<template>
  <div class="container">
    <div id="card-element">
    </div>
    <button @click="submit">Submit Payment</button>
    <div v-if="show_result">{{result_message}}</div>
  </div>

</template>

<script>
export default {
  data() {
    return {
      card: null,
      stripe: Stripe("stripe_id"),
      show_result: false,
      result_message: ""
    };
  },
  mounted() {
    const elements = this.stripe.elements();
    this.card = elements.create("card");
    this.card.mount("#card-element");
  },
  methods: {
    submit() {
      const self = this;
      self.show_result = false;
      this.stripe.createToken(this.card).then(result => {
        console.log("result: " + JSON.stringify(result));
        // エラーの場合
        if (result.error) {
          self.show_result = true;
          self.result_message = result.error.message;
          // 成功の場合
        } else {
          self.show_result = true;
          self.result_message = "token_id: " + result.token.id;
        }
      });
    }
  }
};
</script>

<style scoped>
</style>

成功の場合にトークンを表示してるだけなので、ここにサーバにトークンを投げる処理を入れるといいと思います

おわりに

簡単にカード決済を導入できて便利ですね〜
お金系はバグが怖いからシンプルにできるのは嬉しい

それではよきStripeライフを〜

33
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
28