Last active
December 18, 2016 17:20
-
-
Save MrPowerGamerBR/4a6c4b8c9950a3967f2e0fe5f8d34996 to your computer and use it in GitHub Desktop.
My own MercadoPago API implementation for Java, because the official one was using very old dependencies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mrpowergamerbr.sparklysunnyfunny.utils; | |
import java.io.UnsupportedEncodingException; | |
import java.net.URLEncoder; | |
import java.time.ZonedDateTime; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.apache.commons.lang3.StringUtils; | |
import com.google.gson.Gson; | |
/** | |
* SunnyMercadoPago - Minha própria versão do SDK do MercadoPago, drag and drop. | |
* | |
* Prefira usar o Getters em vez de usar as variáveis públicas. Eu só deixo elas públicas por | |
* conveniência mesmo | |
* | |
* @author MrPowerGamerBR (Leonardo) | |
*/ | |
public class SunnyMercadoPago { | |
public static final Gson gson = new Gson(); | |
public String ACCESS_TOKEN; | |
public String client_id; | |
public String client_token; | |
public static final String END_POINT = "https://api.mercadopago.com"; | |
// Argentina: MLA; Brasil: MLB; Mexico: MLM; Venezuela: MLV; Colombia: MCO | |
public static final String ARGENTINA = "MLA"; | |
public static final String BRASIL = "MLB"; | |
public static final String MEXICO = "MLM"; | |
public static final String VENEZUELA = "MLV"; | |
public static final String COLOMBIA = "MCO"; | |
public SunnyMercadoPago(String client_id, String client_token) { | |
this.client_id = client_id; | |
this.client_token = client_token; | |
} | |
public static void main(String[] args) { | |
SunnyMercadoPago mp = new SunnyMercadoPago(MercadoTokens.client_id, MercadoTokens.client_token); | |
} | |
public String getAccessToken() { | |
String response = HttpRequest.post(END_POINT + "/oauth/token") | |
.part("grant_type", "client_credentials") | |
.part("client_id", this.client_id) | |
.part("client_secret", this.client_token) | |
.body(); | |
AccessTokenResponse webResponse = gson.fromJson(response, AccessTokenResponse.class); | |
this.ACCESS_TOKEN = webResponse.getAccessToken(); | |
return ACCESS_TOKEN; | |
} | |
public PaymentResponse createPayment(String title, int qty, String currencyId, double price) { | |
PaymentItem payment = new PaymentItem(title, qty, currencyId, price); | |
PaymentRequest paymentReq = new PaymentRequest(); | |
paymentReq.items.add(payment); | |
String response = HttpRequest.post(END_POINT + "/checkout/preferences?access_token=" + getAccessToken()) | |
.acceptJson() | |
.contentType("application/json") | |
.send(gson.toJson(paymentReq)) | |
.body(); | |
PaymentResponse webResponse = gson.fromJson(response, PaymentResponse.class); | |
return webResponse; | |
} | |
public PaymentSearchResponse searchPayments() { | |
return searchPayments(new HashMap<String, Object>()); | |
} | |
public PaymentSearchResponse searchPayments(String country) { | |
return searchPayments(new HashMap<String, Object>(), country); | |
} | |
public PaymentSearchResponse searchPayments(Map<String, Object> filters, String country) { | |
return searchPayments(filters, country, 0, 0); | |
} | |
public PaymentSearchResponse searchPayments(Map<String, Object> filters) { | |
return searchPayments(filters, null); | |
} | |
public PaymentSearchResponse searchPayments(Map<String, Object> filters, String country, long offset, long limit) { | |
if (country != null) { | |
filters.put("site_id", country); // Argentina: MLA; Brasil: MLB; Mexico: MLM; Venezuela: MLV; Colombia: MCO | |
} | |
filters.put("offset", offset); | |
filters.put("limit", limit); | |
String response = HttpRequest.get(END_POINT + "/collections/search?" + buildQuery(filters) + "&access_token=" + getAccessToken()) | |
.acceptJson() | |
.contentType("application/json") | |
.body(); | |
return gson.fromJson(response, PaymentSearchResponse.class); | |
} | |
/** | |
* O MercadoPago só permite procurar até 1000 pagamentos por vez, esse método automatiza o processo e procura todos os pagamentos | |
*/ | |
public ArrayList<PaymentSearchResponse> searchAllPayments() { | |
return searchAllPayments(new HashMap<String, Object>(), null); | |
} | |
/** | |
* O MercadoPago só permite procurar até 1000 pagamentos por vez, esse método automatiza o processo e procura todos os pagamentos | |
*/ | |
public ArrayList<PaymentSearchResponse> searchAllPayments(Map<String, Object> filters) { | |
return searchAllPayments(filters, null); | |
} | |
/** | |
* O MercadoPago só permite procurar até 1000 pagamentos por vez, esse método automatiza o processo e procura todos os pagamentos | |
*/ | |
public ArrayList<PaymentSearchResponse> searchAllPayments(Map<String, Object> filters, String country) { | |
return searchAllPayments(filters, country, 0); | |
} | |
private ArrayList<PaymentSearchResponse> searchAllPayments(Map<String, Object> filters, String country, int offset) { | |
ArrayList<PaymentSearchResponse> paymentList = new ArrayList<PaymentSearchResponse>(); | |
PaymentSearchResponse psr = searchPayments(filters, country, 0, 1000); | |
paymentList.add(psr); | |
if (psr.paging.total >= offset) { | |
offset = offset + 1000; | |
psr = searchPayments(filters, country, offset, 1000); | |
paymentList.add(psr); | |
} | |
return paymentList; | |
} | |
private String buildQuery(Map<String, Object> params) { | |
String[] query = new String[params.size()]; | |
int index = 0; | |
for (String key : params.keySet()) { | |
String val = String.valueOf(params.get(key) != null ? params.get(key) : ""); | |
try { | |
val = URLEncoder.encode(val, "UTF-8"); | |
} catch (UnsupportedEncodingException e) { | |
} | |
query[index++] = key+"="+val; | |
} | |
return StringUtils.join(query, "&"); | |
} | |
public static class AccessTokenResponse { | |
public String access_token; | |
public String refresh_token; | |
public boolean live_mode; | |
public int user_id; | |
public String token_type; | |
public int expires_in; | |
public String scope; | |
public String getAccessToken() { | |
return access_token; | |
} | |
} | |
public static class PaymentSearchResponse { | |
public PaymentPaging paging; | |
public ArrayList<PaymentSearchWrapper> results; | |
} | |
public static class PaymentSearchWrapper { | |
public GeneratedPaymentItem collection; | |
} | |
public static class PaymentPaging { | |
public int total; | |
public int limit; | |
public int offset; | |
} | |
public static class PaymentRequest { | |
public ArrayList<PaymentItem> items = new ArrayList<PaymentItem>(); | |
} | |
public static class PaymentItem { | |
public String id; | |
public String title; | |
public String description; | |
public String category_id; | |
public String picture_url; | |
public String currency_id; | |
public int quantity; | |
public double unit_price; | |
public PaymentItem(String title, int quantity, String currency_id, double unit_price) { | |
this.title = title; | |
this.quantity = quantity; | |
this.currency_id = currency_id; | |
this.unit_price = unit_price; | |
} | |
} | |
public static class GeneratedPaymentItem { | |
public String id; | |
public String site_id; | |
public String date_created; | |
public String date_approved; | |
public String last_modified; | |
public String money_release_date; | |
public String operation_type; | |
public int collector_id; | |
public String sponsor_id; | |
public GeneratedPayer payer; // MercadoPago adora criar negócios diferentes | |
public String external_reference; | |
public int merchant_order_id; | |
public String reason; | |
public String currency_id; | |
public double transaction_amount; | |
public double total_paid_amount; | |
public double shipping_cost; | |
public double account_money_amount; | |
public double mercadopago_fee; | |
public double net_received_amount; | |
public double marketplace_fee; | |
public int coupon_id; | |
public int coupon_amount; | |
public double coupon_fee; | |
public double finance_fee; | |
public String status; | |
public String status_detail; | |
public String status_code; | |
public String released; | |
public String payment_type; | |
public String installments; | |
public double installment_amount; | |
public String deferred_period; | |
public Cardholder cardholder; | |
public String statement_descriptor; | |
public String last_four_digits; | |
public String payment_method_id; | |
public String marketplace; | |
public ArrayList<String> tags; | |
public ArrayList<Refund> refunds; | |
public double amount_refunded; | |
public String notification_url; | |
public String getPaymentTitle() { | |
return reason; | |
} | |
public PaymentStatus getPaymentStatus() { | |
return PaymentStatus.fromString(status); | |
} | |
public ZonedDateTime getDateApproved() { | |
if (date_approved == null) { | |
return null; | |
} | |
return ZonedDateTime.parse(date_approved); | |
} | |
public ZonedDateTime getDateCreated() { | |
if (date_created == null) { | |
return null; | |
} | |
return ZonedDateTime.parse(date_created); | |
} | |
} | |
public static class Refund { | |
public double amount; | |
public int id; | |
public Source source; | |
public String date_created; | |
public long collection_id; | |
public long movement_id; | |
} | |
public static class Source { | |
public String name; | |
public String type; | |
public int id; | |
} | |
public static class Cardholder { | |
public String name; | |
public Identification identification; | |
} | |
public static class GeneratedPayer { | |
public String nickname; | |
public String first_name; | |
public String last_name; | |
public Phone phone; | |
public String email; | |
public int id; | |
public Identification identification; | |
public String getEmail() { | |
return email; | |
} | |
} | |
public static class PaymentResponseRoot { | |
public int status; | |
public PaymentResponse response; | |
} | |
public static class PaymentResponse { | |
public int collector_id; | |
public String operation_type; | |
public ArrayList<PaymentItem> paymentItems; | |
public BackUrls back_urls; | |
public String auto_return; | |
public PaymentMethods payment_methods; | |
public int client_id; | |
public String marketplace; | |
public String marketplace_fee; | |
public Shipments shipments; | |
public String notification_url; | |
public String external_reference; | |
public String additional_info; | |
public boolean expires; | |
public String expiration_date_from; | |
public String expiration_date_to; | |
public String date_created; | |
public String id; | |
public String init_point; | |
public String sandbox_init_point; | |
public String getPaymentLink(boolean isSandbox) { | |
return (isSandbox ? sandbox_init_point : init_point); | |
} | |
} | |
public static class Payer { | |
public String name; | |
public String surname; | |
public String email; | |
public String date_created; | |
public Phone phone; | |
public Identification identification; | |
public Address address; | |
} | |
public static class Phone { | |
public String area_code; | |
public String number; | |
public String extension; | |
} | |
public static class Identification { | |
public String type; | |
public String number; | |
} | |
public static class Address { | |
public String street_name; | |
public String street_number; | |
public String zip_code; | |
} | |
public static class BackUrls { | |
public String success; | |
public String pending; | |
public String failure; | |
} | |
public static class PaymentMethods { | |
public ArrayList<PaymentMethod> excluded_payment_methods; | |
public ArrayList<PaymentType> excluded_payment_types; | |
public String installments; | |
public String default_payment_method_id; | |
public String default_installments; | |
} | |
public static class Shipments { | |
public ShipmentAddress receiver_address; | |
} | |
public static class ShipmentAddress { | |
public String zip_code; | |
public String street_number; | |
public String street_name; | |
public String floor; | |
public String apartment; | |
} | |
public static class PaymentMethod { | |
String id; | |
} | |
public static class PaymentType { | |
String id; | |
} | |
public static enum PaymentStatus { | |
/** | |
* O usuário ainda não completou o processo de pagamento. | |
*/ | |
PENDING, | |
/** | |
* O pagamento foi aprovado e acreditado. | |
*/ | |
APPROVED, | |
/** | |
* O pagamento foi cancelado por uma das parte ou porque o tempo expirou. | |
*/ | |
CANCELLED, | |
/** | |
* Foi feito um chargeback no cartão do comprador. | |
*/ | |
CHARGED_BACK, | |
/** | |
* O pagamento foi rejeitado. O usuário pode tentar novamente. | |
*/ | |
REJECTED, | |
/** | |
* O pagamento foi autorizado, mas ainda não capturado. | |
*/ | |
AUTHORIZED, | |
/** | |
* O pagamento está em revisão. | |
*/ | |
IN_PROCESS, | |
/** | |
* O usuário iniciou uma disputa. | |
*/ | |
IN_MEDIATION, | |
UNKNOWN; | |
public static PaymentStatus fromString(String status) { | |
if (status.equalsIgnoreCase("approved")) { | |
return PaymentStatus.APPROVED; | |
} | |
if (status.equalsIgnoreCase("cancelled")) { | |
return PaymentStatus.CANCELLED; | |
} | |
if (status.equalsIgnoreCase("pending")) { | |
return PaymentStatus.PENDING; | |
} | |
if (status.equalsIgnoreCase("charged_back")) { | |
return PaymentStatus.CHARGED_BACK; | |
} | |
if (status.equalsIgnoreCase("rejected")) { | |
return PaymentStatus.REJECTED; | |
} | |
if (status.equalsIgnoreCase("authorized")) { | |
return PaymentStatus.AUTHORIZED; | |
} | |
if (status.equalsIgnoreCase("in_process")) { | |
return PaymentStatus.IN_PROCESS; | |
} | |
if (status.equalsIgnoreCase("in_mediation")) { | |
return PaymentStatus.IN_MEDIATION; | |
} | |
return PaymentStatus.UNKNOWN; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment