--> -->

skimemo


skimemo - 日記/2019-04-17/NativeScriptのJavaScriptからStripeを使う のバックアップ(No.2)


_ NativeScriptのJavaScriptからStripeを使う

NativeScript+JavaScriptからnativescript-stripeを使うときにはまったのでメモです。

私はNativeScript+JavaScriptでアプリを書いています。(まずこれはお勧めしません。世の中的にはTypeScriptがメジャーなようです)
nativescript-stripeのマニュアルには、以下のように呼び出せとあります。

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 
 
-
-
-
!
-
|
!
!
var Stripe = require('nativescript-stripe').Stripe;
const stripe = new Stripe('yourApiKey');
stripe.createToken(cc, (error,token)=>{
  if(!error){
    //Do something with your token;
 
  }else{
    console.log(error);
  }
});

ところが、これをやるとnewのところで以下のエラーが出て落ちます。

JS: ERROR Error: Uncaught (in promise): TypeError: com.stripe.android.Stripe is not a constructor
JS: TypeError: com.stripe.android.Stripe is not a constructor

どうやらプラグインの定義がJavaScriptからはうまく呼べる形になっていないようです。(何かのバージョンの問題?)

そこで、他のプラグインを参考に以下のようなファイルを1つ作ってみました。

common/stripe-index.js

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
 
 
 
 
 
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var nativescript_stripe = require("nativescript-stripe");
exports.Stripe = nativescript_stripe.Stripe;
exports.Card = nativescript_stripe.Card;


そしてこれを使ってStripeを呼び出します。

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 
 
 
-
-
-
!
-
|
!
!
const stripe = require("../../common/stripe-index");
const card = new stripe.Card('4242424242424242', 12, 21, '111');
const strp = new stripe.Stripe('your_public_key');
strp.createToken(card, (error,token)=>{
    if(!error){
        //Do something with your token;
        console.log('stripe.createToken:success:'+token['id']);
    }else{
        console.log('stripe.createToken:error:'+error);
    }
});

これで無事tokenが返るようになりました。

stripe.createToken:success:tok_1EQ6leBstKlU6P**********

めでたしめでたし。

Category: [NativeScript] - 15:09:03