MercadoPago Dart SDK

Overview

MercadoPago SDK module for Payments integration

Usage

To use this plugin, add mercadopago_sdk as a dependency in your pubspec.yaml file.

  • Basic checkout
  • Customized checkout
  • Generic methods

Basic checkout

Configure your credentials


import 'package:mercadopago_sdk/mercadopago_sdk.dart';

var mp = MP("CLIENT_ID", "CLIENT_SECRET");

Instance with only access token

var mp = MP.fromAccessToken("TOKEN");

Preferences

Get an existent Checkout preference


Future<Map<String, dynamic>> index() async {
    result = await mp.getPreference("PREFERENCE_ID");

    return result;
}

Create a Checkout preference


Future<Map<String, dynamic>> index() async {
    var preference = {
        "items": [
            {
                "title": "Test",
                "quantity": 1,
                "currency_id": "USD",
                "unit_price": 10.4
            }
        ]
    };

    var result = await mp.createPreference(preference);

    return result;
}

Update an existent Checkout preference


Future<Map<String, dynamic>> index() async {
    var preference = {
        "items": [
            {
                "title": "Test Modified",
                "quantity": 1,
                "currency_id": "USD",
                "unit_price": 20.4
            }
        ]
    };

    var result = await mp.updatePreference(id, preference);

    return result;
}

Payments/Collections

Search for payments

Future<Map<String, dynamic>> index() async {
    var filters = {
        "id": None,
        "external_reference": None
    };

    var searchResult = await mp.searchPayment(filters)

    return searchResult;
}

Get payment data

Future<Map<String, dynamic>> index() async {
    paymentInfo = await mp.getPayment("PID");

    return paymentInfo;
}

Cancel (only for pending payments)

Future<Map<String, dynamic>> index() async {
    var result = await mp.cancelPayment("PID");

    // Show result
    return result;
}

Refund (only for accredited payments)

Future<Map<String, dynamic>> index() async {
    var result = await mp.refundPayment("PID");

    // Show result
    return result;
}

Customized checkout

Configure your credentials


import 'package:mercadopago_sdk/mercadopago_sdk.dart';

var mp = MP("ACCESS_TOKEN");

Create payment

mp.post("/v1/payments", data);

Create customer

mp.post("/v1/customers", {"email": "[email protected]"});

Get customer

mp.get("/v1/customers/CUSTOMER_ID");

Generic methods


You can access any other resource from the MercadoPago API using the generic methods:

// Get a resource, with optional URL params. Also you can disable authentication for public APIs
mp.get("/resource/uri", { params, authenticate });

// Create a resource with "data" and optional URL params.
mp.post("/resource/uri", { data, params });

// Update a resource with "data" and optional URL params.
mp.put("/resource/uri", { data, params });

// Delete a resource with optional URL params.
mp.delete("/resource/uri", { params });

For example, if you want to get the Sites list (no params and no authentication):

var result = mp.get("/sites");

print(result);
Comments
  • Error of integration using analyzer

    Error of integration using analyzer

    Because mercadopago_sdk >=1.3.0 depends on test ^1.16.8 which depends on analyzer ^1.0.0, mercadopago_sdk >=1.3.0 requires analyzer ^1.0.0.

    So, because audasiuz depends on both analyzer ^0.40.6 and mercadopago_sdk ^1.3.0, version solving failed. pub get failed (1; So, because audasiuz depends on both analyzer ^0.40.6 and mercadopago_sdk ^1.3.0, version solving failed.)

    opened by LDHrez 1
  • Public key and access token

    Public key and access token

    According MercadoPago documentation to generate a preference, you need a Public Key and Access Token and not a Client Id and Client Secret.

    I tried to get preference sending using de constructor MP('public_key','access_token') but didn't work, so i suppose that the Client id is not the same as Public Key and Client Secret is not the same as Access Token.

    opened by eugenio-tesio 1
  • Error on calling get

    Error on calling get

    Im trying to get users or pay method and I have this error:

    [VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The getter 'keys' was called on null. Receiver: null Tried calling: keys

    If a try by the URL by web i receive the information.

    The caller is:

    mp.get("/v1/payment_methods", authenticate: true, params: {});

    Thanks!

    opened by rmartinezalbano 1
  • preference info

    preference info

    hello! I'm having some problems trying to implement the funcionality "getpreference" It lead's me to an error message.

    the code is:

    import 'dart:async'; import 'package:flutter/material.dart'; import 'package:mood/classes.dart'; import 'package:mood/style/components/textFieldFormularios.dart'; import 'package:mood/style/fonts.dart'; import 'package:flutter_google_pay/flutter_google_pay.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

    class CartaoPage extends StatefulWidget { CartaoPage(this.mediaHeight, this.mediaWidth, {Key key}) : super(key: key); final double mediaHeight; final double mediaWidth;

    @override CartaoPageState createState() => new CartaoPageState(); }

    class CartaoPageState extends State { @override void initState() { super.initState(); }

    @override Widget build(BuildContext context) { MercadoPago mercadoInstance = new MercadoPago(); _makeCustomPayment() async { var environment = 'rest'; // or 'production'

      if (!(await FlutterGooglePay.isAvailable(environment))) {
        print('Google pay not available');
      } else {
        ///docs https://developers.google.com/pay/api/android/guides/tutorial
        PaymentBuilder pb = PaymentBuilder()
          ..addGateway( "PAYMENT_GATEWAY","3359798608018742195")
          ..addTransactionInfo("1.0", "USD")
          ..addAllowedCardAuthMethods(["PAN_ONLY", "CRYPTOGRAM_3DS"])
          ..addAllowedCardNetworks(
              ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"]
          )
          ..addBillingAddressRequired(true)
          ..addPhoneNumberRequired(true)
          ..addShippingAddressRequired(true)
          ..addShippingSupportedCountries(["US", "GB","BR"])
          ..addMerchantInfo("Example");
    
        Result result = await FlutterGooglePay.makeCustomPayment(pb.build()).catchError((error) {
          print(error);
        });
        if (result.status == ResultStatus.SUCCESS) {
          print('Success');
        } else if (result.error != null) {
          print(result.error);
        }
      }
    }
    
    Future<Map<String, dynamic>> index() async {
      var payer = {
        'email': '[email protected]'
      };
      var preference = {
        "items": [
          {
            "title": "Test",
            "quantity": 1,
            "currency_id": "BRL",
            "unit_price": 10.4,
            "payer":payer
          }
        ],
      };
    
      var result = await mercadoInstance.mp.createPreference(preference);
    
      return result;
    }
    
    _launchURL(String url) async {
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
    
    return Scaffold(
      backgroundColor: Color(0xff5c31b8),
      appBar: AppBar(
        backgroundColor: Color(0xff5c31b8),
        elevation: 0,
        actions: <Widget>[],
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: widget.mediaWidth * 0.9,
                  ),
                  child: TextFieldFormulario(
                    context,
                    textInputAction: TextInputAction.next,
                    style: AntipastoTextStyle(
                        color: Colors.white, fontSize: 20.0),
                    labelText: "Numero do Cartão ",
                    labelStyle: AntipastoTextStyle(
                        color: Colors.white, fontSize: 20.0),
                  ),
                ),
              ],
            ),
            FlatButton(
              child: Text('Google Pay'),
              onPressed: ()async{
                _makeCustomPayment();
              },
            ),
            FlatButton(
              child: Text('Mercado Pago'),
              onPressed: ()async{
                var payment = await index();
                print(payment);
                var url = payment['response']["sandbox_init_point"];
                String iDe = payment['response']["id"];
                var result = await mercadoInstance.mp.getPreference(iDe);
                print(result);
              },
            )
          ],
        ),
      )
    );
    

    } }

    it gives me the error message:

    Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'keys' was called on null. Receiver: null Tried calling: keys)

    Thanks

    opened by luisNezi 1
  • Error using it with image_picker

    Error using it with image_picker

    Because mercadopago_sdk 1.2.0 depends on http ^0.12.0 and no versions of mercadopago_sdk match >1.2.0 <2.0.0, mercadopago_sdk ^1.2.0 requires http ^0.12.0. So, because .... depends on both http ^0.13.0 and mercadopago_sdk ^1.2.0, version solving failed.

    opened by joaquinperaza 0
  •  factory and method for access token

    factory and method for access token

    Add new changes

    1. Using factory

      var mp = MP.fromAccessToken('MYACCESSTOKEN');
      var preference = {
              "items": [
                  {
                      "title": "Test",
                      "quantity": 1,
                      "currency_id": "USD",
                      "unit_price": 10.4
                  }
              ]
          };
      var result = await mp.createPreference(preference);```
      
      
    2. Using method

      var mp = MP("CLIENT_ID", "CLIENT_SECRET");
      var preference = {
              "items": [
                  {
                      "title": "Test",
                      "quantity": 1,
                      "currency_id": "USD",
                      "unit_price": 10.4
                  }
              ]
          };
      // Change access token
      mp.setAccessToken('MYACCESSTOKEN');
      var result = await mp.createPreference(preference);```
      
    opened by hostelix 0
  • How do I create a card? No ```createCardToken``` found

    How do I create a card? No ```createCardToken``` found

    I am developing a marketplace in Flutter using this package to access the MercadoPago API to build a Transparent Checkout. However, to add a card, I believe I need the createCardToken function. But it doesn't exist in the package, right? How should I implement the adding card feature?

    opened by LucaDillenburg 2
  • ERROR de seguridad

    ERROR de seguridad

    Como ya lo han reportado, el "quemar" tanto el client id como el client secret y el access token es una brecha de seguridad gigante por lo que no es recomendado el uso de este plugin mientras no haya manera de cifrar esas credenciales.

    opened by neoacevedo 0
  • It's not a issue, it's a doubt

    It's not a issue, it's a doubt

    Can you tell me if with this api i can create a pending payment to be released in X days? I need to meet two scenarios:

    1. user makes a purchase, I hold this amount for 2 days, after two days I cancel and return it, like a guarantee.
    2. user makes a purchase, I hold for 2 days, after the two days I effect the payment.
    opened by mdmota 0
  • Basic Payment Flow Example?

    Basic Payment Flow Example?

    Any chance we could get a basic payment flow as an example? I've read the doc but I think I'm missing a lot of information.

    I have created this so far, but then I'm not sure what's next on the list.

    Future<void> startMP() async {
        MP mercadoPago = MP('6924219732628689', 'yd5kmBOBHhXE24GuOVK9iozt5D8vjyY2');
    
        String token = await mercadoPago.getAccessToken();
    
        var payer = {'email': '[email protected]'};
    
        var preference = {
          "items": [
            {
              "title": "Test01",
              "quantity": 1,
              "currency_id": "USD",
              "unit_price": 0.01,
              "payer": payer,
            }
          ],
        };
    
        var result = await mercadoPago.createPreference(preference);
    
        
      }
    

    What's next? Thank you.

    opened by herrmartell 1
Owner
BMKero's
We Are BMKeros
BMKero's
A native Dart SDK for Stripe.

stripe_fl stripe A native Dart SDK for Stripe. Documentation Initializing import 'package:stripe_fl/stripe_fl.dart'; Stripe.init( produc

Chiziaruhoma Ogbonda 3 May 15, 2020
Stream Chat official Flutter SDK. Build your own chat experience using Dart and Flutter.

Official Flutter packages for Stream Chat Quick Links Register to get an API key for Stream Chat Flutter Chat SDK Tutorial Chat UI Kit Sample apps Thi

Stream 659 Dec 25, 2022
Replaces Flutter's bundled Dart SDK with the macOS arm64 version

This script replaces Flutter's bundled Dart SDK with the macOS arm64 version Get

null 21 Oct 9, 2022
Todo is an Simple Task Management App coded using Dart which is a peogramming language for Flutter SDK(2.5) supports Null Safety 📑🚩

Todo ?? ?? ?? Introduction Todo is an Simple Task Management App coded using Dart which is a peogramming language for Flutter SDK(2.5) supports Null S

navee-ramesh 6 Nov 5, 2022
Flutter-Udemy - - A Udemy clone using Flutter sdk and dart.

udemy_clone A new Flutter project. Below are some images : Getting Started This project is a starting point for a Flutter application. A few resources

Priyam Soni 3 Apr 24, 2022
O school_app é uma Aplicação Mobile para uma escola que foi desenvolvida utilizando Flutter SDK/Dart

O school_app é uma Aplicação Mobile para uma escola que foi desenvolvida utilizando Flutter SDK/Dart(Para o aplicativo móvel), Node.Js (Para a API) e PostgreSQL(Para o Banco de dados).

null 2 May 21, 2022
Dart SDK for StarkNet ✨

⚠️ ⚠️ ⚠️ This package is a work in progress. Do not use in production. ⚠️ ⚠️ ⚠️ starknet.dart Dart SDK for StarkNet ✨ The goal of this dart package is

Gabin Marignier 12 Dec 15, 2022
A Dart SDK for interacting with a Minecraft server using the RCON protocol.

A Dart SDK for interacting with a Minecraft server using the RCON protocol. Package on pub.dev Features Provides an API to connect to, log in to, send

Aidan Lok 2 Oct 4, 2022
a flutter socket client sdk for ezyfox-server

ezyfox-server-flutter-client flutter client for ezyfox server Architecture Offical documentation https://youngmonkeys.org/ezyfox-flutter-client-sdk/ P

Young Monkeys 44 Dec 13, 2022
Avo Inspector SDK for Flutter

Avo Inspector for Flutter @Hacktoberfest Happy Hacktoberfest! This repo is participating, check out the issues we've prepared for you If you need any

Avo 10 Oct 25, 2022
Flutter guide + SDK. Check Community repository for common information.

freeRASP for Flutter freeRASP for Flutter is a part of security SDK for the app shielding and security monitoring. Learn more about provided features

Talsec 63 Dec 26, 2022
Bug reporting SDK for Flutter apps.

Shake for Flutter Flutter plugin for Shake. How to use Install Shake Add Shake to your pubspec.yaml file. dependencies: shake_flutter: ^15.0.0 I

Shake 13 Oct 18, 2022
Flutter版微信SDK.WeChat SDK for flutter.

Fluwx 中文请移步此处 What's Fluwx Fluwx is flutter plugin for WeChatSDK which allows developers to call WeChatSDK native APIs. Join QQ Group now: 892398530。

OpenFlutter 2.7k Jan 3, 2023
RelatedDigital Flutter SDK

Table of Contents Introduction Requirements Installation Platform Integration Android iOS Usage Initializing Push Notifications Requesting Permission

Related Digital 34 Jun 26, 2022
A flutter plugin to get facebook deep links and log app events using the latest Facebook SDK to include support for iOS 14

Facebook Sdk For Flutter LinkedIn GitHub facebook_sdk_flutter allows you to fetch deep links, deferred deep links and log facebook app events. This wa

Saad Farhan 23 Dec 17, 2022
Android ve İOS gibi platformlar için mobil uygulama geliştirmenizi sağlayan bir SDK

Flutter Nedir? Google tarafından 2017 yılında piyasaya sürülmüş açık kaynak kodlu bir araçtır. Android ve İOS gibi platformlar için mobil uygulama gel

Google DSC Galatasaray 24 Mar 16, 2022
A flutter plugin to get android version(SDK INT).

get_sdk_int A new flutter plugin project. Getting Started This project is a starting point for a Flutter plug-in package, a specialized package that i

jinyus 0 Dec 28, 2021
A convenience wrapper for building Flutter apps with PDFTron mobile SDK.

About PDFTron Flutter PDFTron's Flutter PDF library brings smooth, flexible, and stand-alone document viewing and editing solutions using Flutter code

PDFTron Systems Inc. 157 Dec 26, 2022