_ NativeScriptのJavaScriptからStripeを使う
NativeScriptからnativescript-stripeを使うときにはまったのでメモです。
私はNativeScript+JavaScriptでアプリを書いています。(まずこれはお勧めしません。世の中的にはTypeScriptがメジャーなようです)
nativescript-stripeのマニュアルには、以下のように呼び出せとあります。
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){
}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
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を呼び出します。
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){
console.log('stripe.createToken:success:'+token['id']);
}else{
console.log('stripe.createToken:error:'+error);
}
});
|
これで無事tokenが返るようになりました。
stripe.createToken:success:tok_1EQ6leBstKlU6P**********
めでたしめでたし。