Code Monkey home page Code Monkey logo

yoomoney-sdk-java's Introduction

YooMoney SDK for Java

Overview

This Java library contains classes that allows you to do payments and call other methods of YooMoney public API.

Requirements

The library uses:

Usage

Gradle Dependency (jCenter)

Download

To use the library in your project write this code to your build.gradle:

buildscript {
    repositories {
        jcenter()
    }
}

dependencies {
    compile 'com.yoo.money.api:yoomoney-sdk-java:7.2.23'
}

App Registration

To be able to use the library you: the first thing you need to do is to register your application and get your unique client id. To do that please follow the steps described on this page (also available in Russian).

Conception

All API methods are represented as classes in package com.yoo.money.api.methods.

Some methods require an unique id to get the response. To get it use API method instance-id passing your client id. Once obtained instance id can be used to perform those methods.

Do NOT request instance id every time you need to call an API method. Obtain it once, store it safely and reuse it in future requests.

Performing Request

To perform request from com.yoo.money.api.methods package you will need to use ApiClient. For your convenience there is default implementation of the ApiClient called DefaultApiClient. It is suitable for most cases. So the very first thing you need to do, is to create ApiClient.

The minimal implementation will look like this:

ApiClient client = new DefaultApiClient.Builder()
    .setClientId("your_client_id_here")
    .create();

If you want to perform a method that requires user's authentication you need request access token. The easiest way to do this is to get AuthorizationData from a client:

AuthorizationParameters parameters = new AuthorizationParameters.Builder()
    ...
    .create();
AuthorizationData data = client.createAuthorizationData(parameters);

Provided AuthorizationParameters allows you to set request parameters as described here. When created AuthorizationData will have URL and POST parameters for OAuth2 authorization.

To get the result from redirect uri you may want to use AuthorizationCodeResponse.parse(redirectUri) method. If successful the instance of AuthorizationCodeResponse will contain temporary authorization code that must be immediately exchanged for an access token:

// parse redirect uri from web browser
AuthorizationCodeResponse response = AuthorizationCodeResponse.parse(redirectUri);

if (response.error == null) {
    // try to get OAuth2 access token
    Token token = client.execute(new Token.Request(response.code, client.getClientId(), myRedirectUri, myClientSecret));
    if (token.error == null) {
        ... // store token.accessToken safely for future uses

        // and authorize client to perform methods that require user's authentication
        client.setAccessToken(token.accessToken);
    } else {
        handleAuthorizationError(token.error);
    }
} else {
    handleAuthorizationError(response.error);
}

Now you can perform any request with authorized client. For instance, if you want to get InstanceId you can do it like this:

InstanceId instanceId = client.execute(new InstanceId.Request(clientId));
// do something with instance id

Links

  1. YooMoney API (in English, in Russian)
  2. YooMoney Java SDK on Bintray

yoomoney-sdk-java's People

Contributors

aleksandr-rodikov avatar drukarev avatar dsokol-ok avatar exwell avatar iskandarshabaev avatar javster avatar johnkuper avatar lynnfield avatar magdel avatar mbushuev avatar melnikovdv avatar raymank26 avatar romkavt avatar valery1707 avatar werder630 avatar yasevich avatar ysoftware avatar zvorygin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yoomoney-sdk-java's Issues

Test for p2p payment to another wallet

Please add test for payment to another Yandex.Money wallet.
Here is my parameters, fetched from debug print:
amount=1.00&comment=zzzzzzzzzz&to=*******&test_payment=true&message=zzzzzzzzz&pattern_id=p2p
Response always is: status=REFUSED, error=ILLEGAL_PARAMS
What can be a problem, please?

/api/account-info method invocation fails.

Invocation of /api/account-info method fails both on prod and demo servers.

Library: com.yandex.money.api:yandex-money-sdk-java:5.1.6

  1. prod server: https://money.yandex.ru: fails on missing balanceDetails.
--> POST https://money.yandex.ru/api/account-info HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
Cache-Control: no-cache
Accept-Language: ru
Authorization: Bearer xxx.xxx

--> END POST (0-byte body)
<-- HTTP/1.1 200 OK (438ms)
Date: Fri, 19 Aug 2016 10:36:10 GMT
Content-Type: application/json;charset=UTF-8
Connection: keep-alive
Keep-Alive: timeout=120
Vary: Accept-Encoding
Cache-Control: no-cache
Set-Cookie: TS01ca9aab=01f3111baf647fe1851be117f3ab18b9b1690f86f2823a62ad4be8b5c6b5733c1dcbb2976a; Path=/
Transfer-Encoding: chunked
OkHttp-Sent-Millis: 1471602970540
OkHttp-Received-Millis: 1471602970590

{"account":"xxx","balance":0.00,"currency":"643","account_type":"personal","identified":false,"account_status":"anonymous"}
<-- END HTTP (135-byte body)

java.lang.NullPointerException: balanceDetails is null
    at com.yandex.money.api.utils.Common.checkNotNull(Common.java:49)
    at com.yandex.money.api.methods.AccountInfo$Builder.setBalanceDetails(AccountInfo.java:235)
    at com.yandex.money.api.typeadapters.AccountInfoTypeAdapter.deserialize(AccountInfoTypeAdapter.java:117)
    at com.yandex.money.api.typeadapters.AccountInfoTypeAdapter.deserialize(AccountInfoTypeAdapter.java:55)
    at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:825)
    at com.yandex.money.api.typeadapters.BaseTypeAdapter.fromJson(BaseTypeAdapter.java:55)
    at com.yandex.money.api.net.BaseApiRequest.parseResponse(BaseApiRequest.java:79)
    at com.yandex.money.api.net.OAuth2Session.parseResponse(OAuth2Session.java:155)
    at com.yandex.money.api.net.OAuth2Session.execute(OAuth2Session.java:73)
  1. demo server: https://demomoney.yandex.ru: server returns incorrect currency code 10643.
--> POST https://demomoney.yandex.ru/api/account-info HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
Cache-Control: no-cache
Accept-Language: ru
Authorization: Bearer xxx.xxx

--> END POST (0-byte body)
<-- HTTP/1.1 200 OK (319ms)
Date: Fri, 19 Aug 2016 11:04:24 GMT
Content-Type: application/json;charset=UTF-8
Connection: keep-alive
Keep-Alive: timeout=120
Vary: Accept-Encoding
Cache-Control: no-cache
Set-Cookie: TS019d3b22=01a1a1e3913fb944846ac9ab9fb641a261b045230bf4306641b008c319fce4c97a66e723e8; Path=/
Transfer-Encoding: chunked
OkHttp-Sent-Millis: 1471604664774
OkHttp-Received-Millis: 1471604664836

{"account":"xxx","balance":100.00,"currency":"10643","identified":false,"account_type":"personal","account_status":"anonymous","balance_details":{"total":100.00,"available":100.00}}
<-- END HTTP (191-byte body)

java.lang.NullPointerException: currency is null

    at com.yandex.money.api.utils.Common.checkNotNull(Common.java:49)
    at com.yandex.money.api.methods.AccountInfo$Builder.setCurrency(AccountInfo.java:199)
    at com.yandex.money.api.typeadapters.AccountInfoTypeAdapter.deserialize(AccountInfoTypeAdapter.java:113)
    at com.yandex.money.api.typeadapters.AccountInfoTypeAdapter.deserialize(AccountInfoTypeAdapter.java:55)
    at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:825)
    at com.yandex.money.api.typeadapters.BaseTypeAdapter.fromJson(BaseTypeAdapter.java:55)
    at com.yandex.money.api.net.BaseApiRequest.parseResponse(BaseApiRequest.java:79)
    at com.yandex.money.api.net.OAuth2Session.parseResponse(OAuth2Session.java:155)
    at com.yandex.money.api.net.OAuth2Session.execute(OAuth2Session.java:73)

Authorization

How to perform authorization?
How to obtain temporary token, what should be in constant ApiTest.ACCESS_TOKEN ?
Can be aded a test performing authorization with/without client_secret?

Можно закрывать.

Задал вопрос, покопавшись в ваших исходниках нашел ответ, можно закрывать.

Но все же, господа: Второй раз имею дело с вашими api, второй раз приходиться копаться в исходниках, пытаясь понять что как устроено. У вас документация просто отсутствует. Не хотите писать Wiki - пишите хотя бы в docblock'ах нормально. Опенсорсные библиотеки имеют документацию в тысячи раз лучше вашей, а вы ведь на этом деньги зарабатываете.

Third-Party Dependencies

Было-бы разумно не включать в клиентскую библиотеку таких зависимостей как GSON, joda-time и okhttp.

1)Начиная с java8 аналогичная joda-time имплементация включена в стандартный JDK. Причём, похоже на то, что в этой реализации участвовали даже некоторые разработчики из команды joda-time.

  1. Работа с сериализацией JSON возможна по средствам Java Beans. Если по-каким-то причинам вам не подходят стандартные механизмы или нет времени/других ресурсов на парсинг, то обычно такие вещи выносятся за рамки клиентской библиотеки и выставляют наружу интерфейс, принимающий исходниые данные.

  2. Не могу сказать какой из фреймворков okhttp или http://hc.apache.org/ является наиболее часто используемым для трансфера данных, но ни одна из трёх зависимостей что вы включили в обязательные не используется в моём проекте. По-моему более разумно для клиентской библиотеки было-бы следовать паттерну проектирования Facade и реализовать внутренюю инфраструктуру таким образом, чтобы предоставить клиентам возможность выбора провайдера. Либо вовсе реализовать подобные вещи на стандартном JDK.

Да, вы используете для сборки только Gradle. Почему не maven? Есть ли в планах дальнейшая работа над API?(roadmap)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.