stripe_api 1.0.3

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 84

Flutter Stripe API

A flutter plugin to integrate stripe into flutter app. There are other pluging available but I tried a different approach. (This plugin not dependent on any other native stripe library) I start to follow the official Android stripe SDK and replicate it's code into Dart. So far I completed the basic functions which includes:

  • Start Customer Session
  • End Customer Session
  • Get Customer
  • Create Card Token
  • Add Customer Source
  • Remove Customer Source
  • Update Default Source
  • Update Customer Shipping Information (not tested)

This plugin is in very initial stage, I am using it in my personal app. Future plan is to complete all the remaining API. And completing the Example Project with proper UI. And also having a TextInputFormatter for card auto complete and validation.

1.0.3

  • CardNumberFormatter code refactored

1.0.2

  • Fixed minor issue

1.0.1

  • Completed CardNumberFormatter class

1.0.0

  • Fixed publish --dry-run issues/warnings

0.0.1

  • Initial release

example/lib/main.dart

import 'dart:async';
import 'dart:convert' show utf8, json;

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:stripe_api/stripe_api.dart';

const ContentTypeJson = 'application/json';

const _accessToken =
    'MWI4ZDM3MGYzZDc4MDc2NmU4MDI5ZTA5OWEwODcyMjA4N2NmIn0.eyJhdWQiOiIyIiwianRpIjoiYTEyODBlODhkY2Q0MzE2OGQzOGI3MzZmYTdjNDI3ODM2NmVhNjEyMWZkZmQxYjhkMzcwZjNkNzgwNzY2ZTgwMjllMDk5YTA4NzIyMDg3Y2YiLCJpYXQiOjE1MzE0NzI2NjcsIm5iZiI6MTUzMTQ3MjY2NywiZXhwIjoxNTYzMDA4NjY3LCJzdWIiOiIxMyIsInNjb3BlcyI6W119.VekND83ON5NmevzRqU8L1qOh74z4yz3uS6LE48DkU6w2145D6E04COKYZdRc_vwU7cLiaoP3rD5j-4BqNpv6MyyIaIrHKUdZX_dMM9DMt9imAdLRDBPzUL-TehEf0jRrFhQhBhnnaYoJFC1NsEONnr4jMWTfi31poP9wrSwCUl5HE-dINGMG60bAMjub4lwBSvxXwAjTRJqDhcAVliwIHnwvtF2C7LA4MeVQzvQBHpuiBZh_Byi1JJur6nW7PHtkHK6cGeDHI4dZOg4qKwLGFDTlDlNx5i2JnvRnYXdkEjSVvQTHUa5NR4DAxzMm2jD56JUEHJ9BPsydhZLVWMLpm5DdXHie0JFLAKQL2ZRWhjdE1sXJGsb9Mv7snLSt4r4qM73GWTA7clFEbeAH3hyrv4w-rvopt1pOI7S-kfhLwvaoj6uE9AnAfiHuVqNauuermLh1Gvk_3FXzq0NBOcLBMXcNh4W_iIyXHmpHejl4cRx1DYA9glssRZ-z0o9QBvG6bBGHZzsA5wf79_MPyCrQWHkHiC2-bQ8MoKrPCOVtsoceLYVT5diqJOH5Lk0VtJRCmBt_5W8hUVarlHwWdVAN0v-3afl34e5cvk_Liveb4wPbF_o4PI96W1-cVAdyA8qSfInZpbVMa730OBNodGo_2LHxZZU4BR07M7w-3__Nwv0';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  final TextEditingController controller = new TextEditingController();

  @override
  void initState() {
    super.initState();

    Stripe.init('pk_test_your_stripe_key');
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Plugin example app'),
        ),
        body: new Container(
          alignment: Alignment.topCenter,
          child: new Column(
            children: <Widget>[
              new SizedBox(height: 12.0),
              new TextField(
                controller: controller,
                inputFormatters: [
                  CardNumberFormatter(
                    onCardBrandChanged: (brand) {
                      print('onCardBrandChanged : ' + brand);
                    },
                    onCardNumberComplete: (){
                      print('onCardNumberComplete');
                    },
                    onShowError: (isError) {
                      print('Is card number valid ? ${!isError}');
                    }
                  ),
                ],
              ),
              new SizedBox(height: 12.0),
              new FlatButton(
                  onPressed: _startSession, child: new Text('Start Session')),
              new SizedBox(height: 12.0),
              new FlatButton(
                  onPressed: _getCustomer, child: new Text('Get Customer')),
              new SizedBox(height: 12.0),
              new FlatButton(
                  onPressed: _endSession, child: new Text('End Session')),
              new SizedBox(height: 12.0),
              new FlatButton(
                  onPressed: _saveCard, child: new Text('Save Card')),
              new SizedBox(height: 12.0),
              new FlatButton(
                  onPressed: _changeDefaultCard,
                  child: new Text('Change Default')),
              new SizedBox(height: 12.0),
              new FlatButton(
                  onPressed: _deleteCard, child: new Text('Delete Card')),
              new SizedBox(height: 12.0),
            ],
          ),
        ),
      ),
    );
  }

  void _startSession() {
    CustomerSession.initCustomerSession(_createEphemeralKey);
  }

  void _getCustomer() async {
    try {
      final customer = await CustomerSession.instance.retrieveCurrentCustomer();
      print(customer);
    } catch (error) {
      print(error);
    }
  }

  void _endSession() {
    CustomerSession.endCustomerSession();
  }

  void _saveCard() {
    StripeCard card = new StripeCard(
        number: '4242 4242 4242 4242', cvc: '713', expMonth: 5, expYear: 2019);
    card.name = 'Jhonny Bravo';
    Stripe.instance.createCardToken(card).then((c) {
      print(c);
      return CustomerSession.instance.addCustomerSource(c.id);
    }).then((source) {
      print(source);
    }).catchError((error) {
      print(error);
    });
  }

  void _changeDefaultCard() async {
    try {
      final customer = await CustomerSession.instance.retrieveCurrentCustomer();
      final card = customer.sources[1].asCard();
      final v =
          await CustomerSession.instance.updateCustomerDefaultSource(card.id);
      print(v);
    } catch (error) {
      print(error);
    }
  }

  void _deleteCard() async {
    try {
      final customer = await CustomerSession.instance.retrieveCurrentCustomer();
      String id;
      for (var c in customer.sources) {
        StripeCard card = c.asCard();
        if (card != null) {
          id = card.id;
          break;
        }
      }

      final v = await CustomerSession.instance.deleteCustomerSource(id);
      print(v);
    } catch (error) {
      print(error);
    }
  }

  Future<String> _createEphemeralKey(String apiVersion) async {
    final url =
        'https://api.example/generate-ephemeral-key?api_version=$apiVersion';
    print(url);

    final response = await http.get(
      url,
      headers: _getHeaders(accessToken: _accessToken),
    );

    final d = json.decode(response.body);
    print(d);
    if (response.statusCode == 200) {
      final key = json.encode(d['data']);
      return key;
    } else {
      throw Exception('Failed to get token');
    }
  }

  Map<String, String> _getHeaders(
      {String accessToken,
      String acceptType = ContentTypeJson,
      String contentType = ContentTypeJson}) {
    final Map<String, String> headers = new Map<String, String>();
    headers['Accept'] = acceptType;
    if (contentType != null) {
      headers['Content-Type'] = contentType;
    }
    if (accessToken != null) {
      headers['Authorization'] = 'Bearer $accessToken';
    }
    print(headers.toString());

    return headers;
  }
}

class CardItem extends StatelessWidget {
  final StripeCard card;

  const CardItem({Key key, this.card}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  stripe_api: ^1.0.3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:stripe_api/stripe_api.dart';
  
Version Uploaded Documentation Archive
1.0.3 Aug 24, 2018 Go to the documentation of stripe_api 1.0.3 Download stripe_api 1.0.3 archive
1.0.2 Aug 18, 2018 Go to the documentation of stripe_api 1.0.2 Download stripe_api 1.0.2 archive
1.0.1 Aug 18, 2018 Go to the documentation of stripe_api 1.0.1 Download stripe_api 1.0.1 archive
1.0.0 Aug 12, 2018 Go to the documentation of stripe_api 1.0.0 Download stripe_api 1.0.0 archive
0.0.2 Aug 5, 2018 Go to the documentation of stripe_api 0.0.2 Download stripe_api 0.0.2 archive
0.0.1 Aug 5, 2018 Go to the documentation of stripe_api 0.0.1 Download stripe_api 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
76
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
84
Learn more about scoring.

We analyzed this package on Oct 10, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.4
  • Flutter: 0.9.5

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Fix lib/card_number_formatter.dart. (-0.50 points)

Analysis of lib/card_number_formatter.dart reported 1 hint:

line 1 col 8: Unused import: 'dart:math'.

Maintenance suggestions

The description is too short. (-20 points)

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.61.0 <3.0.0
flutter 0.0.0
http ^0.11.3+17 0.11.3+17 0.12.0
Transitive dependencies
async 2.0.8
charcode 1.1.2
collection 1.14.11
http_parser 3.1.3
meta 1.1.6
path 1.6.2
sky_engine 0.0.99
source_span 1.4.1
string_scanner 1.0.4
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test