gerencianetflutter 0.0.1

  • Readme
  • Changelog
  • Installing
  • 45

Gerencianet Flutter #

Gerencianet credit card payment sdk implementation in dart

1 - Getting Started - Getting a Payment Token #

To pay with credit cards, first we're going to need a Payment Token.
The first step is to create an instance of GNConfig with your account code.
When testing we should set isSandbox to true.

final config = GNConfig(accountCode: "your_account_code", isSandbox: true);

All right! Now we're going to use the config to obtain an instance of the api, like so:

final api = GNApi(config: config);

Create an instance of GNCreditCard with the credit card data:

//this is a false credit card number generated online
//this is going to work in sandbox mode
final cc = GNCreditCard(
      number: "4342558146566662",
      brand: "visa",
      expirationMonth: "04",
      expirationYear: "2021",
      cvv: "832",
    );

Finally, you can retrieve the token:

GNPaymentToken gnToken = await api.retrievePaymentToken(cc);

2 - Using the token to make payments #

With the payment token in hands we can now make real payments!
The payment data api requires a lot of data, so bear with me...

2.1 Provide the customer data: #

  //Fake data generated online
  GNCustomer customer = GNCustomer(
      customerName: "John Doe",
      cpf: "630.719.530-46",
      customerBirth: "1990-03-19",
      email: "johndoe@johndoe.com",
      customerPhone: "31987655679",
    );

2.2 Provide the customer address: #

    //Fake data generated online
    GNCustomerAddress address = GNCustomerAddress(
        number: 100,
        city: "Seattle",
        neighborhood: "Some Seattle Neighborhood",
        zipcode: "09380-135",
        state: "AC",
        street: "Some Street in Seattle");

2.3 Put it all together: #

GNPaymentData paymentData = GNPaymentData(customer, address, gnToken);

2.4 Creating your custom payment code: #

Since the code to complete the payment should be in your backend, you should create a simple class to make your life easier.
Here's an example:

import 'dart:convert';
import 'package:gerencianetflutter/gn_charge.dart';
import 'package:gerencianetflutter/gn_payment_data.dart';
import 'package:gerencianetflutter/gn_payment_result.dart';
import 'package:http/http.dart' as http;

class MyEndpoint {
  final String baseURL = "http://localhost:3000";
  final String createChargeRoute = "/sample-charge";
  final String payChargeRoute = "/pay";

  Future<GNCharge> createCharge() async {
    final url = baseURL + createChargeRoute;
    http.Response response = await http.get(url);
    assert(response != null && response.body.isNotEmpty);
    Map<String, dynamic> chargeMap = jsonDecode(response.body);
    return GNCharge.fromMap(chargeMap);
  }

  Future<GNPaymentResult> pay(
    GNCharge charge,
    GNPaymentData paymentData,
  ) async {
    final url = baseURL + payChargeRoute;
    http.Response response = await http.post(
      url,
      body: {
        "payment_data": paymentData.toJSON(),
        "charge_data": charge.toJSON(),
      },
    );
    assert(response != null && response.body.isNotEmpty);
    Map<String, dynamic> paymentResultMap = jsonDecode(response.body);
    return GNPaymentResult.fromMap(paymentResultMap);
  }
}

2.5 Making the payment: #

Using the class written before, this is all you should have to do to complete the payment:

    MyEndpoint myEndpoint = MyEndpoint();
    GNCharge charge = await myEndpoint.createCharge();
    GNPaymentResult paymentResult = await myEndpoint.pay(charge, paymentData);

If you want to see the complete code, check out the test folder.

3 - Backend code #

We're almost there!
I'm going to use nodeJS here to demonstrate how the backend should look like (at least the bare minimum), but you can use many other languages https://dev.gerencianet.com.br/docs/instalacao-da-api.
Bear in mind that this is just for demonstration purposes, in a production environment you should be more careful.

Let's begin by installing nodeJS if you don't have it installed yet: https://nodejs.org/
Create a folder in your computer, open a terminal or windows command prompt, navigate to the folder and let's install express (a minimalist web framework for Node.js), type:

npm install express --save

after a while express should be installed and ready to use.

Also, install body-parser, that's gonna make our lives easier when parsing requests/responses.
Type in the same terminal:

npm install body-parser

Good!

Now for the most important package, the Gerencianet node sdk. Just like the others just type in the terminal:

npm install gn-api-sdk-node

Our little local server is going to have only two routes:
GET /sample-charge: which will create a simple 20 bucks charge and return it as a json
POST /pay: which will pay a generated charge, given the charge id (and a lot of other information needed)

So, here's the code for the server:

const express = require('express')
const Gerencianet = require('gn-api-sdk-node');
const app = express()
var bodyParser = require('body-parser')
const port = 3000

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: false
}))

var options = {
    client_id: 'your_client_id'
    client_secret: 'your_client_secret',
    sandbox: true
}

var gn = Gerencianet(options)

app.get('/sample-charge', async (req, res) => {
    var chargeInput = {
        items: [{
            name: 'Product A',
            value: 1000,
            amount: 2
        }]
    }
    let charge = await gn.createCharge({}, chargeInput)
    res.send(charge)
})

app.post('/pay', async (req, res) => {
    let charge = JSON.parse(req.body.charge_data);
    let params = {
        id: charge.charge_id
    }
    let body = JSON.parse(req.body.payment_data)
    try {
        let paymentRes = await gn.payCharge(params, body)
        res.send(paymentRes)
    } catch (e) {
        console.log(e)
        res.send(e)
    }
})

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

if you installed everything correctly, save this code in a .js file (you can call it anything you like, per convention it's usually named index.js).
Don't forget to fill in the client_id and client_secret obtained from your Gerencianet account panel. You should use your dev keys
Assuming you named the file index.js, type in your terminal:

node index.js

This will start the server, and if you filled the information in the server code correctly, you can open a browser and navigate to http://localhost:3000/sample-charge.
This will generate a charge that can be used in our library.

[0.0.1] - April 21, 2020 #

  • Initial release

Use this package as a library

1. Depend on it

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


dependencies:
  gerencianetflutter: ^0.0.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

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

3. Import it

Now in your Dart code, you can use:


import 'package:gerencianetflutter/gerencianetflutter.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
78
Overall:
Weighted score of the above. [more]
45
Learn more about scoring.

We analyzed this package on Jul 3, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

because of import path [gerencianetflutter] that is in a package requiring null.

Health issues and suggestions

Document public APIs. (-0.78 points)

132 out of 133 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Format lib/gerencianetflutter.dart.

Run flutter format to format lib/gerencianetflutter.dart.

Format lib/gn_charge.dart.

Run flutter format to format lib/gn_charge.dart.

Format lib/gn_constants.dart.

Run flutter format to format lib/gn_constants.dart.

Fix additional 3 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/gn_credit_card.dart (Run flutter format to format lib/gn_credit_card.dart.)
  • lib/gn_payment_token.dart (Run flutter format to format lib/gn_payment_token.dart.)
  • lib/rsa.dart (Run flutter format to format lib/rsa.dart.)

Maintenance suggestions

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package.

Common filename patterns include main.dart, example.dart, and gerencianetflutter.dart. Packages with multiple examples should provide example/README.md.

For more information see the pub package layout conventions.

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

The package description is too short. (-2 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
encrypt ^4.0.0 4.0.2
flutter 0.0.0
http ^0.12.0+4 0.12.1
pointycastle ^1.0.2 1.0.2
Transitive dependencies
args 1.6.0
asn1lib 0.6.5
charcode 1.1.3
clock 1.0.1
collection 1.14.12 1.14.13
convert 2.1.1
crypto 2.1.5
http_parser 3.1.4
meta 1.1.8
path 1.7.0
pedantic 1.9.0 1.9.1
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test