O jeito mais simples e rápido de integrar o Moip a sua aplicação Java
Índice
- Instalação
- Configurando a autenticação
- Configurando o ambiente
- Exemplos de Uso:
- Tratamento de Exceções
- Documentação
- Licença
Adicionar no seu pom.xml:
<dependency>
<groupId>br.com.moip</groupId>
<artifactId>java-sdk</artifactId>
<version>3.2.0</version>
</dependency>
Authentication auth = new BasicAuth("TOKEN", "SECRET");
Authentication auth = new OAuth("TOKEN_OAUTH");
Após definir o tipo de autenticação, é necessário gerar o client, informando em qual environment você quer executar suas ações:
Client client = new Client(Client.SANDBOX, auth);
Agora você pode instanciar a Api:
API api = new API(client);
Order createdOrder = api.order().create(new OrderRequest()
.ownId("order_own_id")
.addItem("Nome do produto", 1, "Mais info...", 100)
.customer(new CustomerRequest()
.ownId("customer_own_id")
.fullname("Jose da Silva")
.email("[email protected]")
.birthdate(new ApiDateRequest().date(new Date()))
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
.phone(new PhoneRequest().setAreaCode("11").setNumber("55443322"))
.shippingAddressRequest(new ShippingAddressRequest().street("Avenida Faria Lima")
.streetNumber("3064")
.complement("12 andar")
.city("São Paulo")
.state("SP")
.district("Itaim")
.country("BRA")
.zipCode("01452-000")
)
)
);
String orderId = "ORD-HPMZSOM611M2";
Order order = api.order().get(orderId);
System.out.println(order.toString());
Payment createdPayment = api.payment().create(new PaymentRequest()
.orderId("ORD-HPMZSOM611M2")
.installmentCount(1)
.fundingInstrument(new FundingInstrumentRequest()
.creditCard(new CreditCardRequest()
.hash(CC_HASH)
.holder(new HolderRequest()
.fullname("Jose Portador da Silva")
.birthdate("1988-10-10")
.phone(new PhoneRequest().setAreaCode("11").setNumber("55667788"))
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
)
)
)
);
Payment createdPayment = api.payment().create(new PaymentRequest()
.orderId("ORD-GOHHIF4Z6PLV")
.installmentCount(1)
.fundingInstrument(new FundingInstrumentRequest()
.boleto(new BoletoRequest()
.expirationDate(new ApiDateRequest().date(new GregorianCalendar(2020, Calendar.NOVEMBER, 10).getTime()))
.logoUri("http://logo.com")
.instructionLines(new InstructionLinesRequest()
.first("Primeira linha")
.second("Segunda linha")
.third("Terceira linha")
)
)
)
);
Para capturar links do boleto:
// Link do Boleto
createdPayment.getLinks().payBoletoLink();
// Link para impressão do boleto
createdPayment.getLinks().payBoletoPrintLink();
Payment payment = api.payment().get(PAYMENT_ID);
System.out.println(payment.toString());
Payment capturedPayment = api.payment().capture("PAY-FRAAY8GN1HSB");
System.out.println(capturedPayment);
Payment cancelledPayment = api.payment().cancelPreAuthorized("PAY-1ECF490M0E25");
System.out.println(cancelledPayment);
Customer customer = api.customer().create(new CustomerRequest()
.ownId("CUS-" + System.currentTimeMillis())
.fullname("Jose da Silva")
.email("[email protected]")
.birthdate(new ApiDateRequest().date(new Date()))
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
.phone(new PhoneRequest().setAreaCode("11").setNumber("55443322"))
.shippingAddressRequest(new ShippingAddressRequest().street("Avenida Faria Lima")
.streetNumber("3064")
.complement("12 andar")
.city("São Paulo")
.state("SP")
.district("Itaim")
.country("BRA")
.zipCode("01452-000")
)
);
System.out.println(customer.toString());
String customerId = "CUS-Q3BL0CAJ2G33";
Customer customer = api.customer().get(customerId);
System.out.println(customer.toString());
FundingInstrument creditCard = api.customer().addCreditCard(
new CustomerRequest()
.fundingInstrument(
new FundingInstrumentRequest()
.creditCard(
new CreditCardRequest()
.number("5555666677778884")
.cvc(123)
.expirationMonth("05")
.expirationYear("18")
.holder(
new HolderRequest()
.fullname("Jose Portador da Silva")
.birthdate("1988-10-10")
.phone(
new PhoneRequest()
.setAreaCode("11")
.setNumber("55667788")
)
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
)
)
)
.id("CUS-1RM8JPVKWEVR")
);
System.out.println(creditCard);
api.customer().deleteCreditCard("CRC-NMNW6VIY2L0T")
NotificationPreference notificationPreference = api.notification().create(
new NotificationPreferenceRequest()
.addEvent("ORDER.*")
.addEvent("PAYMENT.AUTHORIZED")
.addEvent("PAYMENT.CANCELLED")
.target("http://requestb.in/1dhjesw1")
);
NotificationPreference notificationPreference = api.notification().get("NPR-NR0GR85KHL10");
System.out.println(notificationPreference.toString());
api.notification().delete("NPR-NR0GR85KHL10"));
NotificationPreferenceListResponse notificationList = api.notification().list();
Para fazer reembolsos totais basta remover o método
amount
.
Refund refund = api.refund().order(
new RefundRequest("ORD-89SOQ6FMPJPX")
.refundingInstrument(new RefundingInstrumentRequest().creditCard())
.amount(2000)
);
Refund refund = api.refund().order(
new RefundRequest("ORD-GS1FSQ3SO9SY")
.refundingInstrument(new RefundingInstrumentRequest()
.bankAccount(
new BankAccountRequest()
.checking()
.bankNumber("001")
.accountNumber("1234")
.accountCheckNumber("1")
.agencyNumber("4444444")
.agencyCheckNumber("2")
.holder(new HolderRequest()
.fullname("Nome do Portador")
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
)
)
)
.amount(2000)
);
Refund refund = api.refund().payment(
new RefundRequest("PAY-70380H9B6L5R")
.refundingInstrument(new RefundingInstrumentRequest().creditCard())
.amount(2000)
);
Refund refund = api.refund().payment(
new RefundRequest("PAY-E4Q0N9TK0BFW")
.refundingInstrument(new RefundingInstrumentRequest()
.bankAccount(
new BankAccountRequest()
.checking()
.bankNumber("001")
.accountNumber("1234")
.accountCheckNumber("1")
.agencyNumber("4444444")
.agencyCheckNumber("2")
.holder(new HolderRequest()
.fullname("Nome do Portador")
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
)
)
)
.amount(2000)
);
Refund refund = api.refund().get("REF-JR4WALM894UJ");
System.out.println(refund);
Multiorder multiorder = api.multiorder().create(new MultiorderRequest()
.ownId("meu_multiorder_id")
.addOrder(new OrderRequest()
.ownId("pedido_1_id")
.amount(new OrderAmountRequest()
.subtotals(new SubtotalsRequest().shipping(2000))
.currency("BRL")
)
.addItem("Camisa Verde e Amarelo - Brasil", 1, "Seleção Brasileira", 2000)
.customer(new CustomerRequest()
.ownId("customer[1234]")
.fullname("Joao Sousa")
.email("[email protected]")
.birthdate(new ApiDateRequest().date(new GregorianCalendar(1988, Calendar.DECEMBER, 30).getTime()))
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
.phone(new PhoneRequest()
.countryCode("55")
.setAreaCode("11")
.setNumber("66778899"))
.shippingAddressRequest(new ShippingAddressRequest()
.street("Avenida Faria Lima")
.streetNumber("2927")
.zipCode("01234000")
.city("Sao Paulo")
.state("SP")
.complement("8")
.district("Itaim"))
)
.addReceiver(new ReceiverRequest()
.secondary("MPA-E3C8493A06AE", new AmountRequest().fixed(500), false))
.addReceiver(new ReceiverRequest()
.primary("MPA-8D5DBB4EF8B8", new AmountRequest(), true))
)
.addOrder(new OrderRequest()
.ownId("pedido_2_id")
.amount(new OrderAmountRequest()
.subtotals(new SubtotalsRequest().shipping(3000))
.currency("BRL")
)
.addItem("Camisa Preta - Alemanha", 1, "Camiseta da Copa 2014", 1000)
.customer(new CustomerRequest()
.ownId("customer[1234]")
.fullname("Joao Sousa")
.email("[email protected]")
.birthdate(new ApiDateRequest().date(new GregorianCalendar(1988, Calendar.DECEMBER, 30).getTime()))
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
.phone(new PhoneRequest()
.countryCode("55")
.setAreaCode("11")
.setNumber("66778899"))
.shippingAddressRequest(new ShippingAddressRequest()
.street("Avenida Faria Lima")
.streetNumber("2927")
.zipCode("01234000")
.city("Sao Paulo")
.state("SP")
.complement("8")
.district("Itaim"))
)
.addReceiver(new ReceiverRequest()
.primary("MPA-123123123", new AmountRequest())
)
)
);
Multiorder multiorder = api.multiorder().get("MOR-F2R675E1X97P");
System.out.println(multiorder);
Multipayment multipayment = api.multipayment().create(new PaymentRequest()
.orderId("MOR-BMJN4E5LSG6N")
.installmentCount(1)
.delayCapture(false)
.fundingInstrument(
new FundingInstrumentRequest()
.creditCard(
new CreditCardRequest()
.hash(CC_HASH)
.holder(
new HolderRequest()
.fullname("Jose Portador da Silva")
.birthdate("1988-10-10")
.phone(
new PhoneRequest()
.setAreaCode("11")
.setNumber("55667788")
)
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
)
)
)
);
Multipayment multipayment = api.multipayment().create(new PaymentRequest()
.orderId("MOR-F2R675T1X97P")
.installmentCount(1)
.fundingInstrument(new FundingInstrumentRequest()
.boleto(new BoletoRequest()
.expirationDate(new ApiDateRequest().date(new GregorianCalendar(2017, Calendar.SEPTEMBER, 30).getTime()))
.instructionLines(new InstructionLinesRequest()
.first("Primeira linha se instrução")
.second("Segunda linha se instrução")
.third("Terceira linha se instrução")
)
.logoUri("http://")
)
)
);
Multipayment multipayment = api.multipayment().get("MPY-OUGA0AHH2BOF");
System.out.println(multipayment);
Account account = api.account().create(new AccountRequest()
.email("[email protected]")
.type(AccountRequest.Type.MERCHANT)
.transparentAccount(true)
.businessSegment(new AccountRequest.BusinessSegmentRequest("35"))
.site("https://dev.moip.com.br/")
.person(new PersonRequest()
.name("Runscope")
.lastName("Random 9123")
.birthDate(new ApiDateRequest().date(new GregorianCalendar(1990, Calendar.JANUARY, 1).getTime()))
.nationality("BRA")
.birthPlace("Santos")
.taxDocument(TaxDocumentRequest.cpf("953.394.633-46"))
.address(new ShippingAddressRequest()
.street("Av. Brigadeiro Faria Lima")
.streetNumber("434")
.district("Itaim")
.city("São Paulo")
.state("SP")
.country("BRA")
.zipCode("01234000")
)
.phone(new PhoneRequest()
.countryCode("55")
.setAreaCode("11")
.setNumber("965213244")
)
.identityDocument(new IdentityDocumentRequest()
.number("434322344")
.issuer("SSP")
.issueDate(new ApiDateRequest().date(new GregorianCalendar(2000, Calendar.DECEMBER, 12).getTime()))
.type(IdentityDocumentRequest.Type.RG)
)
)
.company(new CompanyRequest()
.name("Teste LTDA")
.businessName("Teste")
.address(new ShippingAddressRequest()
.street("Av. Brigadeiro Faria Lima")
.streetNumber("4530")
.district("Itaim")
.city("São Paulo")
.state("SP")
.country("BRA")
.zipCode("01234000")
)
.mainActivity(new CompanyRequest.MainActivityRequest()
.cnae("82.91-1/00")
.description("Atividades de cobranças e informações cadastrais")
)
.taxDocument(TaxDocumentRequest.cnpj("61.148.461/0001-09"))
.openingDate(new ApiDateRequest().date(new GregorianCalendar(2000, Calendar.JANUARY, 1).getTime()))
.phone(new PhoneRequest()
.countryCode("55")
.setAreaCode("11")
.setNumber("975142244")
)
)
);
Account account = api.account().get("MPA-AE2OAL41CBG1");
System.out.println(account);
api.account().checkAccountExists("123.456.798-91");
Payment payment = api.payment().create(
new PaymentRequest()
.orderId("ORD-3435DIB58HYN")
.installmentCount(1)
.escrow(new PaymentRequest.EscrowRequest("Teste de descricao"))
.fundingInstrument(new FundingInstrumentRequest()
.creditCard(
new CreditCardRequest()
.number("4012001037141112")
.cvc(123)
.expirationMonth("05")
.expirationYear("18")
.holder(
new HolderRequest()
.fullname("Jose Portador da Silva")
.birthdate("1988-10-10")
.phone(
new PhoneRequest()
.setAreaCode("11")
.setNumber("55667788")
)
.taxDocument(TaxDocumentRequest.cpf("22222222222"))
)
)
)
);
System.out.println(payment);
Escrow escrow = api.escrow().release("ECW-S0QEDXJM7TXT");
System.out.println(escrow);
String authURL = api.connect().getAuthorizeUrl("APP-XT5FIAK2F8I7",
"http://localhost/moip/callback.php",
new ScopePermissionList(ScopePermission.DEFINE_PREFERENCES
, ScopePermission.MANAGE_ACCOUNT_INFO
, ScopePermission.RECEIVE_FUNDS
, ScopePermission.REFUND
, ScopePermission.RETRIEVE_FINANCIAL_INFO
, ScopePermission.TRANSFER_FUNDS
)
);
System.out.println(authURL);
Connect connect = api.connect().authorize(new ConnectRequest()
.clientId("APP-XT5FIAK2F8I7")
.clientSecret("e2bd3951b87e469eb0f2c2b781a753d5")
.code("8870af1372ada7a18fdff4fa4ca1a60f4d542272")
.redirectUri("http://localhost/moip-sdk/callback")
.grantType(GrantType.authorization_code)
);
System.out.println(connect);
Connect connect = api.connect().authorize(new ConnectRequest()
.refreshToken("80ca5fb244674117be068d2535ecbe2f_v2")
.grantType(GrantType.refresh_token)
);
System.out.println(connect);
Quando ocorre algum erro na API, é lançada a exceção UnexpectedException para erros inesperados e ValidationException para erros de validação.
try {
Payment createdPayment = api.payment().create(
//...
);
} catch(UnexpectedException e) {
//StatusCode >= 500
} catch(ValidationException e) {
//StatusCode entre 400 e 499 (exceto 401)
}