--> -->

skimemo


skimemo - 日記/2019-04-17/NativeScriptのJavaScriptからStripeを使う

_ NativeScriptのJavaScriptからStripeを使う

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

私はNativeScript+JavaScriptでアプリを書いています。(世の中的にはNativeScriptに合わせるのはTypeScriptがメジャーなようで、そちらの方が情報が多いです。なのでこれから始める方は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**********

めでたしめでたし。

_ トラブル例

上記の問題が発生する前には、以下のようなエラーも出ていました。

TypeError: Cannot read property 'CardInputWidget' of undefined
File: "file:///data/data/org.nativescript.SCOP/files/app/tns_modules/nativescript-stripe/stripe.js, line: 226, column: 52

これは、nativescriptとandroid platformのバージョンを最新にすることで解消しました。(逆に言うと今後のupdateで再度エラーになる可能性も・・・)
tns infoで現在のバージョンを確認の上、

npm install -g nativescript
tns platform update

で最新に更新できます。

Category: [NativeScript] - 15:09:03



 
Last-modified: 2019-05-06 (月) 11:31:13 (1809d)