22 | * This POJO class is used only for example purposes - you don't need need it in your code.
23 | */
24 | public class ItemInfo {
25 | private final String name;
26 | private final int imageResourceId;
27 |
28 | // Micros are used for prices to avoid rounding errors when converting between currencies.
29 | private final long priceMicros;
30 |
31 | public ItemInfo(String name, long price, int imageResourceId) {
32 | this.name = name;
33 | this.priceMicros = price;
34 | this.imageResourceId = imageResourceId;
35 | }
36 |
37 | public String getName() {
38 | return name;
39 | }
40 |
41 | public int getImageResourceId() {
42 | return imageResourceId;
43 | }
44 |
45 | public long getPriceMicros() {
46 | return priceMicros;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/support/SideSpaceItemDecoration.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.support;
2 |
3 | import android.content.Context;
4 | import android.graphics.Rect;
5 |
6 | import androidx.recyclerview.widget.RecyclerView;
7 |
8 | import android.view.View;
9 |
10 | public class SideSpaceItemDecoration extends RecyclerView.ItemDecoration {
11 |
12 | private float spacingInDP;
13 | private int spanCount;
14 | private boolean includeEdge;
15 |
16 | public SideSpaceItemDecoration(Context context, int spacing, int spanCount, boolean includeEdge) {
17 |
18 | spacingInDP = spacing * context.getResources().getDisplayMetrics().density;
19 | this.spanCount = spanCount;
20 | this.includeEdge = includeEdge;
21 | }
22 |
23 | @Override
24 | public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
25 | int position = parent.getChildAdapterPosition(view);
26 | int column = position % spanCount;
27 |
28 | if (includeEdge) {
29 | outRect.left = (int) (spacingInDP - column * spacingInDP / spanCount);
30 | outRect.right = (int) ((column + 1) * spacingInDP / spanCount);
31 |
32 | if (position < spanCount) {
33 | outRect.top = (int) spacingInDP;
34 | }
35 | outRect.bottom = (int) spacingInDP;
36 | } else {
37 | outRect.left = (int) (column * spacingInDP / spanCount);
38 | outRect.right = (int) (spacingInDP - (column + 1) * spacingInDP / spanCount);
39 | if (position >= spanCount) {
40 | outRect.top = (int) spacingInDP;
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v21/pay_with_google_button_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
22 |
26 |
29 |
30 |
33 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/api/models/Transaction.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.api.models;
2 |
3 | import androidx.annotation.Nullable;
4 |
5 | import com.google.gson.annotations.SerializedName;
6 |
7 | public class Transaction {
8 |
9 | @SerializedName("TransactionId")
10 | private String id;
11 |
12 | @Nullable
13 | @SerializedName("ReasonCode")
14 | private int reasonCode;
15 |
16 | @Nullable
17 | @SerializedName("CardHolderMessage")
18 | private String cardHolderMessage;
19 |
20 | // 3DS Begin
21 | @Nullable
22 | @SerializedName("PaReq")
23 | private String paReq;
24 |
25 | @Nullable
26 | @SerializedName("AcsUrl")
27 | private String acsUrl;
28 | // 3DS End
29 |
30 | public String getId() {
31 | return id;
32 | }
33 |
34 | public void setId(String id) {
35 | this.id = id;
36 | }
37 |
38 | @Nullable
39 | public int getReasonCode() {
40 | return reasonCode;
41 | }
42 |
43 | public void setReasonCode(@Nullable int reasonCode) {
44 | this.reasonCode = reasonCode;
45 | }
46 |
47 | @Nullable
48 | public String getCardHolderMessage() {
49 | return cardHolderMessage;
50 | }
51 |
52 | public void setCardHolderMessage(@Nullable String cardHolderMessage) {
53 | this.cardHolderMessage = cardHolderMessage;
54 | }
55 |
56 | @Nullable
57 | public String getPaReq() {
58 | return paReq;
59 | }
60 |
61 | public void setPaReq(@Nullable String paReq) {
62 | this.paReq = paReq;
63 | }
64 |
65 | @Nullable
66 | public String getAcsUrl() {
67 | return acsUrl;
68 | }
69 |
70 | public void setAcsUrl(@Nullable String acsUrl) {
71 | this.acsUrl = acsUrl;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.aar
4 | *.ap_
5 | *.aab
6 |
7 | # Files for the ART/Dalvik VM
8 | *.dex
9 |
10 | # Java class files
11 | *.class
12 |
13 | # Generated files
14 | bin/
15 | gen/
16 | out/
17 | # Uncomment the following line in case you need and you don't have the release build type files in your app
18 | # release/
19 |
20 | # Gradle files
21 | .gradle/
22 | build/
23 |
24 | # Local configuration file (sdk path, etc)
25 | local.properties
26 |
27 | # Proguard folder generated by Eclipse
28 | proguard/
29 |
30 | # Log Files
31 | *.log
32 |
33 | # Android Studio Navigation editor temp files
34 | .navigation/
35 |
36 | # Android Studio captures folder
37 | captures/
38 |
39 | # IntelliJ
40 | *.iml
41 | .idea/workspace.xml
42 | .idea/tasks.xml
43 | .idea/gradle.xml
44 | .idea/assetWizardSettings.xml
45 | .idea/dictionaries
46 | .idea/libraries
47 | # Android Studio 3 in .gitignore file.
48 | .idea/caches
49 | .idea/modules.xml
50 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you
51 | .idea/navEditor.xml
52 |
53 | # Keystore files
54 | # Uncomment the following lines if you do not want to check your keystore files in.
55 | #*.jks
56 | #*.keystore
57 |
58 | # External native build folder generated in Android Studio 2.2 and later
59 | .externalNativeBuild
60 | .cxx/
61 |
62 | # Google Services (e.g. APIs or Firebase)
63 | # google-services.json
64 |
65 | # Freeline
66 | freeline.py
67 | freeline/
68 | freeline_project_description.json
69 |
70 | # fastlane
71 | fastlane/report.xml
72 | fastlane/Preview.html
73 | fastlane/screenshots
74 | fastlane/test_output
75 | fastlane/readme.md
76 |
77 | # Version control
78 | vcs.xml
79 |
80 | # lint
81 | lint/intermediates/
82 | lint/generated/
83 | lint/outputs/
84 | lint/tmp/
85 | # lint/reports/
86 |
87 | # Android Profiling
88 | *.hprof
89 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
14 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
30 |
31 |
35 |
36 |
37 |
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/api/ApiMap.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.api;
2 |
3 | import java.io.UnsupportedEncodingException;
4 | import java.net.URLEncoder;
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | public final class ApiMap extends HashMap {
9 |
10 | private static final String TOKEN = "token";
11 |
12 | private ApiMap() { }
13 |
14 | public static Builder builder() {
15 | return new Builder();
16 | }
17 |
18 | private static String urlEncodeUTF8(String s) {
19 | try {
20 | return URLEncoder.encode(s, "UTF-8");
21 | } catch (UnsupportedEncodingException e) {
22 | throw new UnsupportedOperationException(e);
23 | }
24 | }
25 |
26 | private static String urlEncodeUTF8(Map, ?> map) {
27 | StringBuilder sb = new StringBuilder();
28 | for (Entry,?> entry : map.entrySet()) {
29 | if (sb.length() > 0) {
30 | sb.append("&");
31 | }
32 | sb.append(String.format("%s=%s",
33 | urlEncodeUTF8(entry.getKey().toString()),
34 | urlEncodeUTF8(entry.getValue().toString())
35 | ));
36 | }
37 | return sb.toString();
38 | }
39 |
40 | public static class Builder {
41 |
42 | private ApiMap apiMap = new ApiMap();
43 |
44 | private Builder() { }
45 |
46 | public Builder withSession() {
47 | /*User user = RepositoryProvider.provideUserRepository().getCurrentUser();
48 | if (user != null) {
49 | String token = user.getToken();
50 | if (token != null) {
51 | apiMap.put(TOKEN, token);
52 | }
53 | }*/
54 |
55 | return this;
56 | }
57 |
58 | public ApiMap build() {
59 | return apiMap;
60 | }
61 |
62 | public String buildIntoQuery() {
63 | return urlEncodeUTF8(apiMap);
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/pay_with_google_button_no_shadow.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
25 |
32 |
39 |
40 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/pay_with_google_button.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
26 |
33 |
40 |
41 |
47 |
48 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/pay_with_google_button_short_no_shadow.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
25 |
32 |
39 |
40 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/pay_with_google_button_short.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
26 |
33 |
40 |
41 |
47 |
48 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_list_cart.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
17 |
18 |
24 |
25 |
35 |
36 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/api/PayApiFactory.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.api;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 |
6 | import java.util.concurrent.TimeUnit;
7 |
8 | import androidx.annotation.NonNull;
9 | import okhttp3.OkHttpClient;
10 | import okhttp3.logging.HttpLoggingInterceptor;
11 | import retrofit2.Retrofit;
12 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
13 | import retrofit2.converter.gson.GsonConverterFactory;
14 | import ru.cloudpayments.demo.api.interfaces.PayMethods;
15 |
16 | public class PayApiFactory {
17 | private static final String HOST = "https://wp-demo.cloudpayments.ru/";
18 | private static final String API_URL = "";
19 |
20 | private static final int TIMEOUT = 10;
21 | private static final int WRITE_TIMEOUT = 20;
22 | private static final int CONNECT_TIMEOUT = 10;
23 | private static final HttpLoggingInterceptor LOGGING_INTERCEPTOR = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
24 |
25 | public static final String API_ENDPOINT = HOST + API_URL;
26 |
27 | // API implementations
28 | public static PayMethods getPayMethods() {
29 | return getRetrofit().create(PayMethods.class);
30 | }
31 | // API implementations
32 |
33 | private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
34 | .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
35 | .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
36 | .readTimeout(TIMEOUT, TimeUnit.SECONDS)
37 | .addInterceptor(LOGGING_INTERCEPTOR)
38 | .build();
39 |
40 | private static final Gson GSON = new GsonBuilder()
41 | .setLenient()
42 | .create();
43 |
44 | @NonNull
45 | private static Retrofit getRetrofit() {
46 | return new Retrofit.Builder()
47 | .baseUrl(API_ENDPOINT)
48 | .addConverterFactory(GsonConverterFactory.create(GSON))
49 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
50 | .client(CLIENT)
51 | .build();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
16 |
17 |
24 |
25 |
32 |
33 |
39 |
40 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/api/ShopApiFactory.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.api;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 |
6 | import androidx.annotation.NonNull;
7 |
8 | import java.util.concurrent.TimeUnit;
9 |
10 | import okhttp3.OkHttpClient;
11 | import okhttp3.logging.HttpLoggingInterceptor;
12 | import retrofit2.Retrofit;
13 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
14 | import retrofit2.converter.gson.GsonConverterFactory;
15 | import ru.cloudpayments.demo.api.interfaces.ShopMethods;
16 |
17 | public class ShopApiFactory {
18 | private static final String HOST = "https://wp-demo.cloudpayments.ru/index.php/wp-json/";
19 | private static final String API_URL = "wc/v3/";
20 |
21 | private static final int TIMEOUT = 10;
22 | private static final int WRITE_TIMEOUT = 20;
23 | private static final int CONNECT_TIMEOUT = 10;
24 | private static final HttpLoggingInterceptor LOGGING_INTERCEPTOR = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
25 |
26 | public static final String API_ENDPOINT = HOST + API_URL;
27 |
28 | // API implementations
29 | public static ShopMethods getShopMethods() {
30 | return getRetrofit().create(ShopMethods.class);
31 | }
32 | // API implementations
33 |
34 | private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
35 | .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
36 | .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
37 | .readTimeout(TIMEOUT, TimeUnit.SECONDS)
38 | .addInterceptor(LOGGING_INTERCEPTOR)
39 | .build();
40 |
41 | private static final Gson GSON = new GsonBuilder()
42 | .setLenient()
43 | .create();
44 |
45 | @NonNull
46 | private static Retrofit getRetrofit() {
47 | return new Retrofit.Builder()
48 | .baseUrl(API_ENDPOINT)
49 | .addConverterFactory(GsonConverterFactory.create(GSON))
50 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
51 | .client(CLIENT)
52 | .build();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 |
5 | compileSdkVersion 29
6 | defaultConfig {
7 | applicationId "ru.cloudpayments.demo"
8 | minSdkVersion 19
9 | targetSdkVersion 29
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 |
14 | configurations {
15 | all*.exclude group: 'com.android.support', module: 'support-v13'
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | compileOptions {
26 | targetCompatibility 1.8
27 | sourceCompatibility 1.8
28 | }
29 |
30 | lintOptions {
31 | checkReleaseBuilds false
32 | abortOnError false
33 | }
34 |
35 | useLibrary 'org.apache.http.legacy'
36 | }
37 |
38 | dependencies {
39 |
40 | implementation 'androidx.appcompat:appcompat:1.1.0'
41 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
42 | implementation 'com.google.android.material:material:1.1.0'
43 | implementation 'androidx.cardview:cardview:1.0.0'
44 |
45 | // gPay
46 | implementation 'com.google.android.gms:play-services-wallet:18.0.0'
47 |
48 | // CloudPayments SDK
49 | implementation 'ru.cloudpayments.android:sdk:1.0.8'
50 | //implementation project(path: ':sdk')
51 |
52 | // views binding
53 | implementation 'com.jakewharton:butterknife:10.1.0'
54 | annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
55 |
56 | // material dialogs
57 | implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
58 |
59 | // rx
60 | implementation 'io.reactivex.rxjava2:rxjava:2.2.9'
61 | implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
62 |
63 | // http
64 | implementation 'com.squareup.retrofit2:retrofit:2.5.0'
65 | implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
66 | implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
67 | implementation 'com.squareup.okhttp3:okhttp:3.14.1'
68 | implementation 'com.squareup.okhttp3:logging-interceptor:3.14.1'
69 |
70 | // event bus
71 | implementation 'org.greenrobot:eventbus:3.1.1'
72 |
73 | // image loading and caching
74 | implementation 'com.github.bumptech.glide:glide:4.9.0'
75 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_list_product.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
17 |
18 |
25 |
26 |
35 |
36 |
44 |
45 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/sdk/src/main/java/ru/cloudpayments/sdk/cp_card/CPCardType.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.sdk.cp_card;
2 |
3 | public class CPCardType {
4 |
5 | public final static int UNKNOWN = -1;
6 | public final static int VISA = 0;
7 | public final static int MASTER_CARD = 1;
8 | public final static int MAESTRO = 2;
9 | public final static int MIR = 3;
10 | public final static int JCB = 4;
11 |
12 | public static String toString(int value) {
13 | switch (value) {
14 | case VISA:
15 | return "Visa";
16 | case MASTER_CARD:
17 | return "MasterCard";
18 | case MAESTRO:
19 | return "Maestro";
20 | case MIR:
21 | return "MIR";
22 | case JCB:
23 | return "JCB";
24 | default:
25 | return "Unknown";
26 | }
27 | }
28 |
29 | public static int fromString(String value) {
30 | if ("visa".equals(value.toLowerCase())) {
31 | return VISA;
32 | } else if ("mastercard".equals(value.toLowerCase())) {
33 | return MASTER_CARD;
34 | } else if ("maestro".equals(value.toLowerCase())) {
35 | return MAESTRO;
36 | } else if ("mir".equals(value.toLowerCase())) {
37 | return MIR;
38 | } else if ("jcb".equals(value.toLowerCase())) {
39 | return JCB;
40 | } else {
41 | return UNKNOWN;
42 | }
43 | }
44 |
45 | public static int getType(String creditCardNumberPart) {
46 |
47 | if (creditCardNumberPart == null || creditCardNumberPart.isEmpty())
48 | return UNKNOWN;
49 |
50 | int first = Integer.valueOf(creditCardNumberPart.substring(0, 1));
51 |
52 | if (first == 4)
53 | return VISA;
54 |
55 | if (first == 6)
56 | return MAESTRO;
57 |
58 | if (creditCardNumberPart.length() < 2)
59 | return UNKNOWN;
60 |
61 | int firstTwo = Integer.valueOf(creditCardNumberPart.substring(0, 2));
62 |
63 | if (firstTwo == 35)
64 | return JCB;
65 |
66 | if (firstTwo == 50 || (firstTwo >= 56 && firstTwo <= 58))
67 | return MAESTRO;
68 |
69 | if (firstTwo >= 51 && firstTwo <= 55)
70 | return MASTER_CARD;
71 |
72 | if (creditCardNumberPart.length() < 4)
73 | return UNKNOWN;
74 |
75 | int firstFour = Integer.valueOf(creditCardNumberPart.substring(0, 4));
76 |
77 | if (firstFour >= 2200 && firstFour <= 2204)
78 | return MIR;
79 |
80 | if (firstFour >= 2221 && firstFour <= 2720)
81 | return MASTER_CARD;
82 |
83 | return UNKNOWN;
84 | }
85 | }
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/api/models/PayRequestArgs.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.api.models;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class PayRequestArgs {
6 |
7 | @SerializedName("amount")
8 | private String amount; // Сумма платежа (Обязательный)
9 |
10 | @SerializedName("currency")
11 | private String currency; // Валюта (Обязательный)
12 |
13 | @SerializedName("name")
14 | private String name; // Имя держателя карты в латинице (Обязательный для всех платежей кроме Apple Pay и Google Pay)
15 |
16 | @SerializedName("card_cryptogram_packet")
17 | private String cardCryptogramPacket; // Криптограмма платежных данных (Обязательный)
18 |
19 | @SerializedName("invoice_id")
20 | private String invoiceId; // Номер счета или заказа в вашей системе (необязательный)
21 |
22 | @SerializedName("description")
23 | private String description; // Описание оплаты в свободной форме (необязательный)
24 |
25 | @SerializedName("account_id")
26 | private String accountId; // Идентификатор пользователя в вашей системе (необязательный)
27 |
28 | @SerializedName("json_data")
29 | private String jsonData; // Любые другие данные, которые будут связаны с транзакцией (необязательный)
30 |
31 | public String getAmount() {
32 | return amount;
33 | }
34 |
35 | public void setAmount(String amount) {
36 | this.amount = amount;
37 | }
38 |
39 | public String getCurrency() {
40 | return currency;
41 | }
42 |
43 | public void setCurrency(String currency) {
44 | this.currency = currency;
45 | }
46 |
47 | public String getName() {
48 | return name;
49 | }
50 |
51 | public void setName(String name) {
52 | this.name = name;
53 | }
54 |
55 | public String getCardCryptogramPacket() {
56 | return cardCryptogramPacket;
57 | }
58 |
59 | public void setCardCryptogramPacket(String cardCryptogramPacket) {
60 | this.cardCryptogramPacket = cardCryptogramPacket;
61 | }
62 |
63 | public String getInvoiceId() {
64 | return invoiceId;
65 | }
66 |
67 | public void setInvoiceId(String invoiceId) {
68 | this.invoiceId = invoiceId;
69 | }
70 |
71 | public String getDescription() {
72 | return description;
73 | }
74 |
75 | public void setDescription(String description) {
76 | this.description = description;
77 | }
78 |
79 | public String getAccountId() {
80 | return accountId;
81 | }
82 |
83 | public void setAccountId(String accountId) {
84 | this.accountId = accountId;
85 | }
86 |
87 | public String getJsonData() {
88 | return jsonData;
89 | }
90 |
91 | public void setJsonData(String jsonData) {
92 | this.jsonData = jsonData;
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/sdk/src/main/java/ru/cloudpayments/sdk/cp_card/api/CPCardApi.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.sdk.cp_card.api;
2 |
3 | import android.content.Context;
4 |
5 | import com.android.volley.Request;
6 | import com.android.volley.RequestQueue;
7 | import com.android.volley.Response;
8 | import com.android.volley.VolleyError;
9 | import com.android.volley.toolbox.StringRequest;
10 | import com.android.volley.toolbox.Volley;
11 | import com.google.gson.Gson;
12 | import com.google.gson.GsonBuilder;
13 |
14 | import ru.cloudpayments.sdk.cp_card.api.models.BinInfo;
15 | import ru.cloudpayments.sdk.cp_card.api.models.BinInfoResponse;
16 |
17 | public class CPCardApi {
18 |
19 | public interface CompleteBinInfoListener {
20 |
21 | void onCompleted(final BinInfo binInfo);
22 | }
23 |
24 | public interface ErrorListener {
25 |
26 | void onError(final String message);
27 | }
28 |
29 | private final Context context;
30 | private final Gson gson;
31 |
32 | public CPCardApi(Context context) {
33 | this.context = context;
34 | this.gson = createGson();
35 | }
36 |
37 | private Gson createGson() {
38 | return new GsonBuilder()
39 | .setLenient()
40 | .create();
41 | }
42 |
43 | public void getBinInfo(String firstSixDigits, final CompleteBinInfoListener completeListener, final ErrorListener errorListener) {
44 |
45 | firstSixDigits = firstSixDigits.replace(" ", "");
46 |
47 | if (firstSixDigits.length() < 6) {
48 | errorListener.onError("You must specify the first 6 digits of the card number");
49 | return;
50 | }
51 |
52 | firstSixDigits = firstSixDigits.substring(0, 6);
53 |
54 | RequestQueue queue = Volley.newRequestQueue(context);
55 | String url ="https://api.cloudpayments.ru/bins/info/" + firstSixDigits;
56 |
57 | StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
58 | new Response.Listener() {
59 | @Override
60 | public void onResponse(String response) {
61 |
62 | BinInfoResponse binInfoResponse = gson.fromJson(response, BinInfoResponse.class);
63 |
64 | if (binInfoResponse.isSuccess() && binInfoResponse.getBinInfo() != null) {
65 | completeListener.onCompleted(binInfoResponse.getBinInfo());
66 | } else {
67 | errorListener.onError("Unable to determine bank");
68 | }
69 |
70 | }
71 | }, new Response.ErrorListener() {
72 | @Override
73 | public void onErrorResponse(VolleyError error) {
74 | errorListener.onError(error.getMessage());
75 | }
76 | });
77 |
78 | queue.add(stringRequest);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/screens/cart/CartActivity.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.screens.cart;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.os.Bundle;
6 | import androidx.recyclerview.widget.GridLayoutManager;
7 | import android.widget.TextView;
8 |
9 | import butterknife.BindView;
10 | import butterknife.OnClick;
11 | import ru.cloudpayments.demo.R;
12 | import ru.cloudpayments.demo.base.BaseListActivity;
13 | import ru.cloudpayments.demo.managers.CartManager;
14 | import ru.cloudpayments.demo.models.Product;
15 | import ru.cloudpayments.demo.screens.checkout.CheckoutActivity;
16 | import ru.cloudpayments.demo.support.SideSpaceItemDecoration;
17 |
18 | public class CartActivity extends BaseListActivity implements CartAdapter.OnClickListener {
19 |
20 | @BindView(R.id.text_total)
21 | TextView textViewTotal;
22 |
23 | @Override
24 | protected int getLayoutId() {
25 | return R.layout.activity_cart;
26 | }
27 |
28 | @Override
29 | protected void onCreate(Bundle savedInstanceState) {
30 | setTheme(R.style.AppTheme);
31 | super.onCreate(savedInstanceState);
32 |
33 | setTitle(R.string.cart_title);
34 |
35 | initList();
36 | initTotal();
37 | }
38 |
39 | private void initList() {
40 | GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
41 |
42 | recyclerView.addItemDecoration(new SideSpaceItemDecoration(this, 16,1, true));
43 |
44 | adapter = new CartAdapter();
45 | adapter.setHasStableIds(true);
46 | adapter.setListener(this);
47 |
48 | recyclerView.setLayoutManager(layoutManager);
49 | recyclerView.setAdapter(adapter);
50 |
51 | adapter.update(CartManager.getInstance().getProducts());
52 | }
53 |
54 | private void initTotal() {
55 |
56 | int total = 0;
57 |
58 | for (Product product : CartManager.getInstance().getProducts()) {
59 | total += Integer.parseInt(product.getPrice());
60 | }
61 |
62 | textViewTotal.setText(getString(R.string.cart_total) + " " + total + " " + getString(R.string.main_rub));
63 | }
64 |
65 | @OnClick(R.id.text_phone)
66 | void onPhoneClick() {
67 | String phone = getString(R.string.main_phone);
68 | Intent intent = new Intent(Intent.ACTION_DIAL);
69 | intent.setData(Uri.parse("tel:" + phone));
70 | startActivity(intent);
71 | }
72 |
73 | @OnClick(R.id.text_email)
74 | void onEmailClick() {
75 | String email = getString(R.string.main_email);
76 | Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + email));
77 | startActivity(Intent.createChooser(emailIntent, getString(R.string.main_select_app)));
78 | }
79 |
80 | @Override
81 | public void onProductClick(Product item) {
82 |
83 | }
84 |
85 | @OnClick(R.id.button_go_to_payment)
86 | void onGoToPaymentClick() {
87 | startActivity(new Intent(this, CheckoutActivity.class));
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
25 |
26 |
35 |
36 |
44 |
45 |
56 |
57 |
64 |
65 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/api/PayApi.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.api;
2 |
3 | import io.reactivex.Observable;
4 | import ru.cloudpayments.demo.api.models.PayRequestArgs;
5 | import ru.cloudpayments.demo.api.models.Post3dsRequestArgs;
6 | import ru.cloudpayments.demo.api.models.Transaction;
7 | import ru.cloudpayments.demo.api.response.PayApiResponse;
8 |
9 | public class PayApi {
10 |
11 | private static final String CONTENT_TYPE = "application/json";
12 |
13 | public static Observable charge(String cardCryptogramPacket, String cardHolderName, int amount) {
14 |
15 | // Параметры:
16 | PayRequestArgs args = new PayRequestArgs();
17 | args.setAmount(Integer.toString(amount)); // Сумма платежа (Обязательный)
18 | args.setCurrency("RUB"); // Валюта (Обязательный)
19 | args.setName(cardHolderName); // Имя держателя карты в латинице (Обязательный для всех платежей кроме Apple Pay и Google Pay)
20 | args.setCardCryptogramPacket(cardCryptogramPacket); // Криптограмма платежных данных (Обязательный)
21 | args.setInvoiceId("1122"); // Номер счета или заказа в вашей системе (необязательный)
22 | args.setDescription("Оплата цветов"); // Описание оплаты в свободной форме (необязательный)
23 | args.setAccountId("123"); // Идентификатор пользователя в вашей системе (необязательный)
24 | args.setJsonData("{\"age\":27,\"name\":\"Ivan\",\"phone\":\"+79998881122\"}"); // Любые другие данные, которые будут связаны с транзакцией (необязательный)
25 |
26 | return PayApiFactory.getPayMethods()
27 | .charge(CONTENT_TYPE, args)
28 | .flatMap(PayApiResponse::handleError)
29 | .map(PayApiResponse::getData);
30 | }
31 |
32 | public static Observable auth(String cardCryptogramPacket, String cardHolderName, int amount) {
33 |
34 | // Параметры:
35 | PayRequestArgs args = new PayRequestArgs();
36 | args.setAmount(Integer.toString(amount)); // Сумма платежа (Обязательный)
37 | args.setCurrency("RUB"); // Валюта (Обязательный)
38 | args.setName(cardHolderName); // Имя держателя карты в латинице (Обязательный для всех платежей кроме Apple Pay и Google Pay)
39 | args.setCardCryptogramPacket(cardCryptogramPacket); // Криптограмма платежных данных (Обязательный)
40 | args.setInvoiceId("1122"); // Номер счета или заказа в вашей системе (необязательный)
41 | args.setDescription("Оплата цветов"); // Описание оплаты в свободной форме (необязательный)
42 | args.setAccountId("123"); // Идентификатор пользователя в вашей системе (необязательный)
43 | args.setJsonData("{\"age\":27,\"name\":\"Ivan\",\"phone\":\"+79998881122\"}"); // Любые другие данные, которые будут связаны с транзакцией (необязательный)
44 |
45 | return PayApiFactory.getPayMethods()
46 | .auth(CONTENT_TYPE, args)
47 | .flatMap(PayApiResponse::handleError)
48 | .map(PayApiResponse::getData);
49 | }
50 |
51 | public static Observable post3ds(String transactionId, String paRes) {
52 |
53 | Post3dsRequestArgs args = new Post3dsRequestArgs();
54 | args.setTransactionId(transactionId);
55 | args.setPaRes(paRes);
56 |
57 | return PayApiFactory.getPayMethods()
58 | .post3ds(CONTENT_TYPE, args)
59 | .flatMap(PayApiResponse::handleError)
60 | .map(PayApiResponse::getData);
61 | }
62 | }
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/googlepay/ConstantsGPay.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.googlepay;
2 |
3 | import android.util.Pair;
4 |
5 | import com.google.android.gms.wallet.WalletConstants;
6 |
7 | import java.util.Arrays;
8 | import java.util.List;
9 |
10 | import ru.cloudpayments.demo.support.Constants;
11 |
12 | public class ConstantsGPay {
13 | // This file contains several constants you must edit before proceeding. Once you're done,
14 | // remove this static block and run the sample.
15 | // Before you start, please take a look at PaymentsUtil.java to see where the constants are used
16 | // and to potentially remove ones not relevant to your integration.
17 | // Required changes:
18 | // 1. Update SUPPORTED_NETWORKS and SUPPORTED_METHODS if required (consult your processor if
19 | // unsure).
20 | // 2. Update CURRENCY_CODE to the currency you use.
21 | // 3. Update SHIPPING_SUPPORTED_COUNTRIES to list the countries where you currently ship. If
22 | // this is not applicable to your app, remove the relevant bits from PaymentsUtil.java.
23 | // 4. If you're integrating with your processor / gateway directly, update
24 | // GATEWAY_TOKENIZATION_NAME and GATEWAY_TOKENIZATION_PARAMETERS per the instructions they
25 | // provided. You don't need to update DIRECT_TOKENIZATION_PUBLIC_KEY.
26 | // 5. If you're using direct integration, please consult the documentation to learn about
27 | // next steps.
28 |
29 | // Changing this to ENVIRONMENT_PRODUCTION will make the API return real card information.
30 | // Please refer to the documentation to read about the required steps needed to enable
31 | // ENVIRONMENT_PRODUCTION.
32 | public static final int PAYMENTS_ENVIRONMENT = WalletConstants.ENVIRONMENT_TEST;
33 |
34 | // The allowed networks to be requested from the API. If the user has cards from networks not
35 | // specified here in their account, these will not be offered for them to choose in the popup.
36 | public static final List SUPPORTED_NETWORKS = Arrays.asList(
37 | WalletConstants.CARD_NETWORK_VISA,
38 | WalletConstants.CARD_NETWORK_MASTERCARD
39 | );
40 |
41 | public static final List SUPPORTED_METHODS = Arrays.asList(
42 | // PAYMENT_METHOD_CARD returns to any card the user has stored in their Google Account.
43 | WalletConstants.PAYMENT_METHOD_CARD,
44 |
45 | // PAYMENT_METHOD_TOKENIZED_CARD refers to cards added to Android Pay, assuming Android
46 | // Pay is installed.
47 | // Please keep in mind cards may exist in Android Pay without being added to the Google
48 | // Account.
49 | WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD
50 | );
51 |
52 | // Required by the API, but not visible to the user.
53 | public static final String CURRENCY_CODE = "RUB";
54 |
55 | // The name of your payment processor / gateway. Please refer to their documentation for
56 | // more information.
57 | public static final String GATEWAY_TOKENIZATION_NAME = "cloudpayments";
58 |
59 | // Custom parameters required by the processor / gateway.
60 | // In many cases, your processor / gateway will only require a gatewayMerchantId.
61 | // Please refer to your processor's documentation for more information. The number of parameters
62 | // required and their names vary depending on the processor.
63 | public static final List> GATEWAY_TOKENIZATION_PARAMETERS = Arrays.asList(
64 | Pair.create("gatewayMerchantId", Constants.MERCHANT_PUBLIC_ID)
65 | );
66 |
67 | private ConstantsGPay() {
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/screens/main/MainActivity.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.screens.main;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.os.Bundle;
6 | import android.view.Menu;
7 | import android.view.MenuItem;
8 |
9 | import androidx.recyclerview.widget.GridLayoutManager;
10 |
11 | import butterknife.OnClick;
12 | import io.reactivex.android.schedulers.AndroidSchedulers;
13 | import io.reactivex.schedulers.Schedulers;
14 | import ru.cloudpayments.demo.R;
15 | import ru.cloudpayments.demo.api.ShopApi;
16 | import ru.cloudpayments.demo.base.BaseListActivity;
17 | import ru.cloudpayments.demo.managers.CartManager;
18 | import ru.cloudpayments.demo.models.Product;
19 | import ru.cloudpayments.demo.screens.cart.CartActivity;
20 | import ru.cloudpayments.demo.support.SideSpaceItemDecoration;
21 |
22 | public class MainActivity extends BaseListActivity implements ProductsAdapter.OnClickListener {
23 |
24 | @Override
25 | protected int getLayoutId() {
26 | return R.layout.activity_main;
27 | }
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | setTheme(R.style.AppTheme);
32 | super.onCreate(savedInstanceState);
33 |
34 | getSupportActionBar().setDisplayHomeAsUpEnabled(false);
35 |
36 | setTitle(R.string.main_title);
37 |
38 | initList();
39 |
40 | getProducts();
41 | }
42 |
43 | private void initList() {
44 | GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
45 |
46 | recyclerView.addItemDecoration(new SideSpaceItemDecoration(this, 16,2, true));
47 |
48 | adapter = new ProductsAdapter();
49 | adapter.setHasStableIds(true);
50 | adapter.setListener(this);
51 |
52 | recyclerView.setLayoutManager(layoutManager);
53 | recyclerView.setAdapter(adapter);
54 | }
55 |
56 | @OnClick(R.id.text_phone)
57 | void onPhoneClick() {
58 | String phone = getString(R.string.main_phone);
59 | Intent intent = new Intent(Intent.ACTION_DIAL);
60 | intent.setData(Uri.parse("tel:" + phone));
61 | startActivity(intent);
62 | }
63 |
64 | @OnClick(R.id.text_email)
65 | void onEmailClick() {
66 | String email = getString(R.string.main_email);
67 | Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + email));
68 | startActivity(Intent.createChooser(emailIntent, getString(R.string.main_select_app)));
69 | }
70 |
71 | @Override
72 | public boolean onCreateOptionsMenu(Menu menu) {
73 | getMenuInflater().inflate(R.menu.main, menu);
74 | return super.onCreateOptionsMenu(menu);
75 | }
76 |
77 | @Override
78 | public boolean onOptionsItemSelected(MenuItem item) {
79 | switch (item.getItemId()) {
80 | case R.id.action_cart: {
81 | if (CartManager.getInstance().getProducts().isEmpty()) {
82 | showToast(R.string.main_cart_is_empty);
83 | } else {
84 | startActivity(new Intent(this, CartActivity.class));
85 | }
86 | }
87 | }
88 |
89 | return super.onOptionsItemSelected(item);
90 | }
91 |
92 | @Override
93 | public void onProductClick(Product item) {
94 | CartManager.getInstance().getProducts().add(item);
95 | showToast(R.string.main_product_added_to_cart);
96 | }
97 |
98 | private void getProducts() {
99 | compositeDisposable.add(ShopApi
100 | .getProducts()
101 | .subscribeOn(Schedulers.io())
102 | .observeOn(AndroidSchedulers.mainThread())
103 | .doOnSubscribe(disposable -> showLoading())
104 | .doOnEach(notification -> hideLoading())
105 | .subscribe(products -> {
106 | adapter.update(products);
107 | }, this::handleError));
108 | }
109 |
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/pay_with_google_button_short_content.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
23 |
28 |
33 |
38 |
43 |
48 |
49 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_cart.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
22 |
23 |
33 |
34 |
46 |
47 |
62 |
63 |
76 |
77 |
84 |
85 |
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CloudPayments Demo
3 |
4 | My Online Store
5 | Unfortunately, Pay with Google is not available on this phone.
6 | Checking if Pay with Google is available...
7 | Successfully received payment data for %s!
8 |
9 | Оплатить через Google
10 |
11 |
12 | Загрузка данных
13 | Пожалуйста, подождите…
14 | Для этого действия необходима авторизация
15 | Сервер недоступен
16 |
17 |
18 | Отсутствует соединение с интернетом
19 |
20 |
21 | CloudPayments
22 | Посмотрите, как выглядят платежи через CloudPayments для покупателей в мобильном приложении. Выберите товары, которые нужно приобрести. Товары не настоящие, платежи тоже — деньги тратить не придется.
23 | В корзину
24 | +7 495 374-78-60
25 | sales@cloudpayments.ru
26 | Выберите приложение
27 | Ваша корзина пуста добавьте один или несколько товаров чтобы продолжить.
28 | Товар добавлен в корзину.
29 | Руб.
30 |
31 | Одностадийная оплата
32 | Двухстадийная оплата
33 |
34 |
35 |
36 | Корзина
37 | Итого:
38 | Перейти к оплате
39 |
40 |
41 | Оплата
42 | Так выглядят платежи через CloudPayments для покупателей в мобильном приложении. Платеж тестовый — деньги тратить не придется. Мы не ограничиваем своих клиентов в использовании какой либо определенной формы для ввода карточных данных, вы можете создать любую форму которая будет полностью соответсвовать дизайну вашего приложения.
43 | Всего к оплате:
44 | Номер карты
45 | MM/YY
46 | CVC
47 | Владелец карты
48 | Оплатить
49 |
50 |
51 | ВНИМАНИЕ!\nВ режиме PRODUCTION с вашей банковской карты будет списан 1 рубль!
52 | Вы можете провести оплату введя данные банковской карты или используя Google Pay если этот сервис доступен на Вашем устройстве
53 | Срок действия в формате: MMYY
54 | Имя владельца
55 | CVV код
56 | Оплатить
57 | или
58 |
59 | Номер карты некорректен
60 | Срок действитя некорректен либо истек
61 | Некорректный CVC код
62 |
63 | Невозможно создать криптограмму проверьте данные карты
64 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-ja/pay_with_google_button_content.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
23 |
28 |
33 |
38 |
43 |
48 |
49 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/base/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.demo.base;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 | import android.view.MenuItem;
7 | import android.widget.Toast;
8 |
9 | import com.afollestad.materialdialogs.MaterialDialog;
10 |
11 | import org.greenrobot.eventbus.EventBus;
12 | import org.greenrobot.eventbus.Subscribe;
13 |
14 | import java.net.UnknownHostException;
15 | import java.util.Arrays;
16 | import java.util.List;
17 |
18 | import androidx.annotation.LayoutRes;
19 | import androidx.annotation.Nullable;
20 | import androidx.annotation.StringRes;
21 | import androidx.appcompat.app.AppCompatActivity;
22 | import androidx.appcompat.widget.Toolbar;
23 | import butterknife.BindView;
24 | import butterknife.ButterKnife;
25 | import io.reactivex.disposables.CompositeDisposable;
26 | import ru.cloudpayments.demo.R;
27 | import ru.cloudpayments.demo.api.events.EmptyEvent;
28 | import ru.cloudpayments.demo.api.response.PayApiError;
29 |
30 | public abstract class BaseActivity extends AppCompatActivity {
31 |
32 | protected final String TAG = "TAG_" + getClass().getSimpleName().toUpperCase();
33 |
34 | protected CompositeDisposable compositeDisposable = new CompositeDisposable();
35 |
36 | @Nullable
37 | @BindView(R.id.toolbar)
38 | protected Toolbar toolbar;
39 |
40 | protected int toolbarTitleId;
41 |
42 | private MaterialDialog loadingDialog;
43 |
44 | @LayoutRes
45 | protected abstract int getLayoutId();
46 |
47 | @Override
48 | public void setContentView(@LayoutRes int layoutResID) {
49 | super.setContentView(layoutResID);
50 | ButterKnife.bind(this);
51 | }
52 |
53 | @Override
54 | protected void onCreate(@Nullable Bundle savedInstanceState) {
55 | super.onCreate(savedInstanceState);
56 | setContentView(getLayoutId());
57 |
58 | if (toolbar != null) {
59 | setSupportActionBar(toolbar);
60 |
61 | assert getSupportActionBar() != null;
62 | getSupportActionBar().setDisplayHomeAsUpEnabled(true);
63 | }
64 |
65 | initLoadingDialog();
66 | }
67 |
68 | private void initLoadingDialog() {
69 | loadingDialog = new MaterialDialog
70 | .Builder(this)
71 | .progress(true, 0)
72 | .title(R.string.dialog_loading_title)
73 | .content(R.string.dialog_loading_content)
74 | .cancelable(false)
75 | .build();
76 | }
77 |
78 | @Nullable
79 | public Toolbar getToolbar() {
80 | return toolbar;
81 | }
82 |
83 | @Override
84 | protected void onStart() {
85 | super.onStart();
86 | EventBus.getDefault().register(this);
87 | }
88 |
89 | @Override
90 | protected void onStop() {
91 | super.onStop();
92 | EventBus.getDefault().unregister(this);
93 | }
94 |
95 | /*@Override
96 | public void onDestroy() {
97 | super.onDestroy();
98 | compositeSubscription.unsubscribe();
99 | }*/
100 |
101 | public void showLoading() {
102 | if (loadingDialog.isShowing()) {
103 | return;
104 | }
105 |
106 | loadingDialog.show();
107 | }
108 |
109 | @Override
110 | public void setTitle(int titleId) {
111 | super.setTitle(titleId);
112 |
113 | toolbarTitleId = titleId;
114 | }
115 |
116 | public void hideLoading() {
117 | if (!loadingDialog.isShowing()) {
118 | return;
119 | }
120 |
121 | loadingDialog.dismiss();
122 | }
123 |
124 | @Override
125 | public boolean onOptionsItemSelected(MenuItem item) {
126 | switch (item.getItemId()) {
127 | case android.R.id.home: {
128 | onBackPressed();
129 | return true;
130 | }
131 | }
132 |
133 | return super.onOptionsItemSelected(item);
134 | }
135 |
136 | @Override
137 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
138 | super.onActivityResult(requestCode, resultCode, data);
139 | }
140 |
141 | @Subscribe
142 | public void onNothing(EmptyEvent event) {
143 | }
144 |
145 | public void showToast(@StringRes int resId) {
146 | showToast(getString(resId));
147 | }
148 |
149 | public void showToast(String message) {
150 | Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
151 | }
152 |
153 | public void log(String message) {
154 | Log.d(TAG, message);
155 | }
156 |
157 | public void handleError(Throwable throwable, Class... ignoreClasses) {
158 |
159 | if (ignoreClasses.length > 0) {
160 | List classList = Arrays.asList(ignoreClasses);
161 |
162 | if (classList.contains(throwable.getClass())) {
163 | return;
164 | }
165 | }
166 |
167 | if (throwable instanceof PayApiError) {
168 | PayApiError apiError = (PayApiError) throwable;
169 |
170 | String message = apiError.getMessage();
171 | showToast(message);
172 | } else if (throwable instanceof UnknownHostException) {
173 | showToast(R.string.common_no_internet_connection);
174 | } else {
175 | showToast(throwable.getMessage());
176 | }
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/sdk/src/main/java/ru/cloudpayments/sdk/three_ds/ThreeDsDialogFragment.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.sdk.three_ds;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.os.Build;
6 | import android.os.Bundle;
7 | import android.view.LayoutInflater;
8 | import android.view.View;
9 | import android.view.ViewGroup;
10 | import android.view.Window;
11 | import android.webkit.JavascriptInterface;
12 | import android.webkit.WebView;
13 | import android.webkit.WebViewClient;
14 |
15 | import androidx.fragment.app.DialogFragment;
16 |
17 | import com.google.gson.JsonObject;
18 | import com.google.gson.JsonParser;
19 |
20 | import org.jsoup.Jsoup;
21 | import org.jsoup.nodes.Document;
22 | import org.jsoup.nodes.Element;
23 |
24 | import java.io.UnsupportedEncodingException;
25 | import java.net.URLEncoder;
26 |
27 | import ru.cloudpayments.sdk.R;
28 |
29 | public class ThreeDsDialogFragment extends DialogFragment {
30 |
31 | private static final String POST_BACK_URL = "https://demo.cloudpayments.ru/WebFormPost/GetWebViewData";
32 |
33 | private static final String ACS_URL = "acs_url";
34 | private static final String MD = "md";
35 | private static final String PA_REQ = "pa_req";
36 | private static final String TERM_URL = "term_url";
37 |
38 | private String acsUrl;
39 | private String md;
40 | private String paReq;
41 | private String termUrl;
42 |
43 | private ThreeDSDialogListener listener;
44 |
45 | private WebView webViewThreeDs;
46 |
47 | public static ThreeDsDialogFragment newInstance(String acsUrl, String md, String paReq) {
48 | ThreeDsDialogFragment dialogFragment = new ThreeDsDialogFragment();
49 | Bundle args = new Bundle();
50 | args.putString(ACS_URL, acsUrl);
51 | args.putString(MD, md);
52 | args.putString(PA_REQ, paReq);
53 | args.putString(TERM_URL, POST_BACK_URL);
54 | dialogFragment.setArguments(args);
55 | return dialogFragment;
56 | }
57 |
58 | @Override
59 | public void onCreate(Bundle savedInstanceState) {
60 | super.onCreate(savedInstanceState);
61 | acsUrl = getArguments().getString(ACS_URL);
62 | md = getArguments().getString(MD);
63 | paReq = getArguments().getString(PA_REQ);
64 | termUrl = getArguments().getString(TERM_URL);
65 | }
66 |
67 | @Override
68 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
69 | View view = inflater.inflate(R.layout.dialog_fragment_three_ds, container, false);
70 | webViewThreeDs = view.findViewById(R.id.web_view_three_ds);
71 | webViewThreeDs.setWebViewClient(new ThreeDsWebViewClient());
72 | webViewThreeDs.getSettings().setDomStorageEnabled(true);
73 | webViewThreeDs.getSettings().setJavaScriptEnabled(true);
74 | webViewThreeDs.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
75 | webViewThreeDs.addJavascriptInterface(new ThreeDsJavaScriptInterface(), "JavaScriptThreeDs");
76 | return view;
77 | }
78 |
79 | @Override
80 | public void onActivityCreated(Bundle savedInstanceState) {
81 | super.onActivityCreated(savedInstanceState);
82 |
83 | try {
84 | String params = new StringBuilder()
85 | .append("PaReq=").append(URLEncoder.encode(paReq, "UTF-8"))
86 | .append("&MD=").append(URLEncoder.encode(md, "UTF-8"))
87 | .append("&TermUrl=").append(URLEncoder.encode(termUrl, "UTF-8"))
88 | .toString();
89 | webViewThreeDs.postUrl(acsUrl, params.getBytes());
90 | } catch (UnsupportedEncodingException e) {
91 | e.printStackTrace();
92 | }
93 | }
94 |
95 | @Override
96 | public void onStart() {
97 | super.onStart();
98 | Window window = getDialog().getWindow();
99 | if (window != null) {
100 | window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
101 | }
102 | }
103 |
104 | private class ThreeDsWebViewClient extends WebViewClient {
105 |
106 | @Override
107 | public void onPageFinished(WebView view, String url) {
108 |
109 | if (url.toLowerCase().equals(POST_BACK_URL.toLowerCase())) {
110 | view.setVisibility(View.GONE);
111 | view.loadUrl("javascript:window.JavaScriptThreeDs.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'');");
112 | }
113 | }
114 | }
115 |
116 | class ThreeDsJavaScriptInterface {
117 |
118 | @SuppressWarnings("unused")
119 | @JavascriptInterface
120 | public void processHTML(final String html) {
121 |
122 | Document doc = Jsoup.parse(html);
123 | Element element = doc.select("body").first();
124 |
125 | JsonParser parser = new JsonParser();
126 | JsonObject jsonObject = parser.parse(element.ownText()).getAsJsonObject();
127 | final String paRes = jsonObject.get("PaRes").getAsString();
128 |
129 | if (paRes != null && !paRes.isEmpty()) {
130 |
131 | if (listener != null) {
132 | getActivity().runOnUiThread(new Runnable() {
133 | @Override
134 | public void run() {
135 | listener.onAuthorizationCompleted(md, paRes);
136 | }
137 | });
138 | }
139 | } else {
140 | if (listener != null) {
141 | getActivity().runOnUiThread(new Runnable() {
142 | @Override
143 | public void run() {
144 | listener.onAuthorizationFailed(html);
145 | }
146 | });
147 | }
148 | }
149 | dismiss();
150 | }
151 | }
152 |
153 | @Override
154 | public void onAttach(Context context) {
155 | super.onAttach(context);
156 | if (context instanceof ThreeDSDialogListener) {
157 | listener = (ThreeDSDialogListener) context;
158 | }
159 | }
160 |
161 | @SuppressWarnings("deprecation")
162 | @Override
163 | public void onAttach(Activity activity) {
164 | super.onAttach(activity);
165 |
166 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
167 | if (activity instanceof ThreeDSDialogListener) {
168 | listener = (ThreeDSDialogListener) activity;
169 | }
170 | }
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/app/src/main/java/ru/cloudpayments/demo/googlepay/PaymentsUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Google Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package ru.cloudpayments.demo.googlepay;
18 |
19 | import android.app.Activity;
20 | import android.util.Pair;
21 |
22 | import com.google.android.gms.tasks.Task;
23 | import com.google.android.gms.wallet.CardRequirements;
24 | import com.google.android.gms.wallet.IsReadyToPayRequest;
25 | import com.google.android.gms.wallet.PaymentDataRequest;
26 | import com.google.android.gms.wallet.PaymentMethodTokenizationParameters;
27 | import com.google.android.gms.wallet.PaymentsClient;
28 | import com.google.android.gms.wallet.TransactionInfo;
29 | import com.google.android.gms.wallet.Wallet;
30 | import com.google.android.gms.wallet.WalletConstants;
31 |
32 | import java.math.BigDecimal;
33 | import java.math.RoundingMode;
34 |
35 | /**
36 | * Contains helper static methods for dealing with the Payments API.
37 | *
38 | * Many of the parameters used in the code are optional and are set here merely to call out their
39 | * existence. Please consult the documentation to learn more and feel free to remove ones not
40 | * relevant to your implementation.
41 | */
42 | public class PaymentsUtil {
43 | private static final BigDecimal MICROS = new BigDecimal(1000000d);
44 |
45 | private PaymentsUtil() {
46 | }
47 |
48 | /**
49 | * Creates an instance of {@link PaymentsClient} for use in an {@link Activity} using the
50 | * environment and theme set in {@link ConstantsGPay}.
51 | *
52 | * @param activity is the caller's activity.
53 | */
54 | public static PaymentsClient createPaymentsClient(Activity activity) {
55 | Wallet.WalletOptions walletOptions = new Wallet.WalletOptions.Builder()
56 | .setEnvironment(ConstantsGPay.PAYMENTS_ENVIRONMENT)
57 | .build();
58 | return Wallet.getPaymentsClient(activity, walletOptions);
59 | }
60 |
61 | /**
62 | * Builds {@link PaymentDataRequest} to be consumed by {@link PaymentsClient#loadPaymentData}.
63 | *
64 | * @param transactionInfo contains the price for this transaction.
65 | */
66 | public static PaymentDataRequest createPaymentDataRequest(TransactionInfo transactionInfo) {
67 | PaymentMethodTokenizationParameters.Builder paramsBuilder =
68 | PaymentMethodTokenizationParameters.newBuilder()
69 | .setPaymentMethodTokenizationType(
70 | WalletConstants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY)
71 | .addParameter("gateway", ConstantsGPay.GATEWAY_TOKENIZATION_NAME);
72 | for (Pair param : ConstantsGPay.GATEWAY_TOKENIZATION_PARAMETERS) {
73 | paramsBuilder.addParameter(param.first, param.second);
74 | }
75 |
76 | return createPaymentDataRequest(transactionInfo, paramsBuilder.build());
77 | }
78 |
79 | private static PaymentDataRequest createPaymentDataRequest(TransactionInfo transactionInfo, PaymentMethodTokenizationParameters params) {
80 | PaymentDataRequest request =
81 | PaymentDataRequest.newBuilder()
82 | .setPhoneNumberRequired(false)
83 | .setEmailRequired(true)
84 | .setShippingAddressRequired(false)
85 | .setTransactionInfo(transactionInfo)
86 | .addAllowedPaymentMethods(ConstantsGPay.SUPPORTED_METHODS)
87 | .setCardRequirements(
88 | CardRequirements.newBuilder()
89 | .addAllowedCardNetworks(ConstantsGPay.SUPPORTED_NETWORKS)
90 | .setAllowPrepaidCards(true)
91 | .setBillingAddressRequired(true)
92 | .build())
93 | .setPaymentMethodTokenizationParameters(params)
94 |
95 | // If the UI is not required, a returning user will not be asked to select
96 | // a card. Instead, the card they previously used will be returned
97 | // automatically (if still available).
98 | // Prior whitelisting is required to use this feature.
99 | .setUiRequired(true)
100 | .build();
101 |
102 | return request;
103 | }
104 |
105 | /**
106 | * Determines if the user is eligible to Pay with Google by calling
107 | * {@link PaymentsClient#isReadyToPay}. The nature of this check depends on the methods set in
108 | * {@link ConstantsGPay#SUPPORTED_METHODS}.
109 | *
110 | * If {@link WalletConstants#PAYMENT_METHOD_CARD} is specified among supported methods, this
111 | * function will return true even if the user has no cards stored. Please refer to the
112 | * documentation for more information on how the check is performed.
113 | *
114 | * @param client used to send the request.
115 | */
116 | public static Task isReadyToPay(PaymentsClient client) {
117 | IsReadyToPayRequest.Builder request = IsReadyToPayRequest.newBuilder();
118 | for (Integer allowedMethod : ConstantsGPay.SUPPORTED_METHODS) {
119 | request.addAllowedPaymentMethod(allowedMethod);
120 | }
121 | return client.isReadyToPay(request.build());
122 | }
123 |
124 | /**
125 | * Builds {@link TransactionInfo} for use with {@link PaymentsUtil#createPaymentDataRequest}.
126 | *
127 | * The price is not displayed to the user and must be in the following format: "12.34".
128 | * {@link PaymentsUtil#microsToString} can be used to format the string.
129 | *
130 | * @param price total of the transaction.
131 | */
132 | public static TransactionInfo createTransaction(String price) {
133 | return TransactionInfo.newBuilder()
134 | .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
135 | .setTotalPrice(price)
136 | .setCurrencyCode(ConstantsGPay.CURRENCY_CODE)
137 | .build();
138 | }
139 |
140 | /**
141 | * Converts micros to a string format accepted by {@link PaymentsUtil#createTransaction}.
142 | *
143 | * @param micros value of the price.
144 | */
145 | public static String microsToString(long micros) {
146 | return new BigDecimal(micros).divide(MICROS).setScale(2, RoundingMode.HALF_EVEN).toString();
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Поддержка этой версии SDK закончена 31.12.2021, эта версия больше не будет обновляться, рекомендуем перейти на новую версию: https://github.com/cloudpayments/CloudPayments-SDK-Android
2 |
3 | # CloudPayments SDK for Android
4 |
5 | CloudPayments SDK позволяет интегрировать прием платежей в мобильные приложение для платформы Android.
6 |
7 | ### Схема работы мобильного приложения:
8 | 
9 | 1. В приложении необходимо получить данные карты: номер, срок действия, имя держателя и CVV;
10 | 2. Создать криптограмму карточных данных при помощи SDK;
11 | 3. Отправить криптограмму и все данные для платежа с мобильного устройства на ваш сервер;
12 | 4. С сервера выполнить оплату через платежное API CloudPayments.
13 |
14 | ### Требования
15 | Для работы CloudPayments SDK необходим Android версии 4.0.3 (API level 15) и выше.
16 |
17 | ### Добавление SDK в ваш проект
18 | Для подключения CloudPayments SDK добавьте в файл build.gradle вашего проекта следующую зависимость:
19 |
20 | ```
21 | implementation 'ru.cloudpayments.android:sdk:1.0.8'
22 | ```
23 | ### Структура проекта:
24 |
25 | * **api** - Пример файлов для проведения платежа через ваш сервер
26 | * **app** - Пример реализации приложения с использованием SDK
27 | * **sdk** - Исходный код SDK
28 |
29 |
30 | ### Подготовка к работе
31 |
32 | Для начала приема платежей через мобильные приложения вам понадобятся:
33 |
34 | * Public ID;
35 | * Пароль для API (**Важно:** Не храните пароль для API в приложении, выполняйте запросы через сервер согласно Схемы работы мобильного приложения).
36 |
37 | Эти данные можно получить в личном кабинете: [https://merchant.cloudpayments.ru/](https://merchant.cloudpayments.ru/) после подключения к [CloudPayments](https://cloudpayments.ru/).
38 |
39 | ### Возможности CloudPayments SDK:
40 |
41 | * Проверка карточного номера на корректность
42 |
43 | ```
44 | boolean CPCard.isValidNumber(String cardNumber);
45 |
46 | ```
47 |
48 | * Проверка срока действия карты
49 |
50 | ```
51 | boolean CPCard.isValidExpDate(String cardDate); // cardDate в формате MMYY
52 |
53 | ```
54 |
55 | * Определение типа платежной системы
56 |
57 | ```
58 | CPCard card = new CPCard(String cardNumber, String cardDate, String cardCVC);
59 | String card.getType();
60 |
61 | ```
62 |
63 | * Определение банка эмитента
64 |
65 | ```
66 | CPCardApi api = new CPCardApi(this);
67 |
68 | // Пример определения банка по номеру карты
69 | api.getBinInfo(cardNumber, binInfo -> {
70 | binInfo.getBankName(); // Название банка
71 | binInfo.getLogoUrl(); // URL картинки логотипа банка
72 | }, message -> {
73 | Log.e("Error", message);
74 | });
75 |
76 | ```
77 |
78 | * Шифрование карточных данных и создание криптограммы для отправки на сервер
79 |
80 | ```
81 | CPCard card = new CPCard(String cardNumber, String cardDate, String cardCVC);
82 | String card.cardCryptogram(String publicId);
83 |
84 | ```
85 |
86 | * Отображение 3DS формы и получении результата 3DS аутентификации
87 |
88 | ```
89 | ThreeDsDialogFragment.newInstance(transaction.getAcsUrl(),
90 | String transactionId,
91 | String paReq)
92 | .show(getFragmentManager(), "3DS");
93 | ```
94 |
95 | ### Пример проведения платежа:
96 |
97 | #### 1) Создание криптограммы
98 |
99 | ```
100 | // Обязательно проверяйте входящие данные карты (номер, срок действия и cvc код) на корректность, иначе при попытке создания объекта CPCard мы получим исключение.
101 | CPCard card = new CPCard(String cardNumber, String cardDate, String cardCVC);
102 | String card.cardCryptogram(String publicId);
103 |
104 | ```
105 |
106 | #### 2) Выполнение запроса на проведения платежа через API CloudPayments
107 |
108 | Платёж - [оплата по криптограмме](https://developers.cloudpayments.ru/#oplata-po-kriptogramme).
109 |
110 | Для привязки карты (платёж "в один клик") используйте метод
111 | [оплату по токену](https://developers.cloudpayments.ru/#oplata-po-tokenu-rekarring).
112 |
113 | Токен можно получить при совершении оплаты по криптограмме, либо при получении [уведомлений](https://developers.cloudpayments.ru/#uvedomleniya).
114 |
115 |
116 | #### 3) Если необходимо, показать 3DS форму для подтверждения платежа
117 |
118 | ```
119 | ThreeDsDialogFragment.newInstance(transaction.getAcsUrl(),
120 | String transactionId,
121 | String paReq)
122 | .show(getFragmentManager(), "3DS");
123 | ```
124 |
125 | Для получения результатов прохождения 3DS аутентификации реализуйте интерефейс ThreeDSDialogListener в Activity из которой происходит создание и отображение ThreeDsDialogFragment.
126 |
127 | ```
128 | public class CheckoutActivity implements ThreeDSDialogListener {
129 | ...
130 | @Override
131 | public void onAuthorizationCompleted(String md, String paRes) {
132 | post3ds(md, paRes); // Успешное прохождение аутентификации, для завершения оплаты выполните запрос API post3ds
133 | }
134 |
135 | @Override
136 | public void onAuthorizationFailed(String html) {
137 | showToast("AuthorizationFailed"); // Неудалось пройти аутентификацию, отобразите ошибку.
138 | }
139 | }
140 | ```
141 |
142 | #### 4) Для завершения оплаты выполнить метод Post3ds
143 |
144 | Смотрите документацию по API: Платёж - [обработка 3-D Secure](https://developers.cloudpayments.ru/#obrabotka-3-d-secure).
145 |
146 | ### Подключение Google Pay через CloudPayments
147 |
148 | [О Google Pay](https://cloudpayments.ru/wiki/integration/products/googlepay)
149 |
150 | [Документация](https://developers.google.com/payments/setup)
151 |
152 | [Пример использования Google Pay API от Google](https://github.com/android-pay/paymentsapi-quickstart)
153 |
154 | #### Включение Google Pay
155 |
156 | В файл build.gradle подключите следующую зависимость:
157 |
158 | ```
159 | implementation 'com.google.android.gms:play-services-wallet:16.0.1'
160 | ```
161 |
162 | В файл манифест приложения добавьте мета информацию:
163 |
164 | ```
165 |
168 | ```
169 |
170 | #### Проведение платежа через Google Pay
171 |
172 | Сконфигурируйте параметры:
173 |
174 | ```
175 | PaymentMethodTokenizationParameters params =
176 | PaymentMethodTokenizationParameters.newBuilder()
177 | .setPaymentMethodTokenizationType(
178 | WalletConstants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY)
179 | .addParameter("gateway", "cloudpayments")
180 | .addParameter("gatewayMerchantId", "Ваш Public ID")
181 | .build();
182 | ```
183 |
184 | Укажите тип оплаты через шлюз (Wallet-Constants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY) и добавьте два параметра:
185 |
186 | 1) gateway: cloudpayments
187 |
188 | 2) gatewayMerchantId: Ваш Public ID, его можно посмотреть в [личном кабинете](https://merchant.cloudpayments.ru/).
189 |
190 | С этими параметрами запросите токен Google Pay:
191 |
192 | ```
193 | String tokenGP = paymentData.getPaymentMethodToken().getToken();
194 | ```
195 |
196 | Используя токен Google Pay в качестве криптограммы карточных данных, совершите платёж методами API, указанными ранее.
197 |
198 | **В случае проведения платежа с токеном Google Pay в качестве имени держателя карты неоходимо указать: "Google Pay"**
199 |
200 | ### Поддержка
201 |
202 | По возникающим вопросам техничечкого характера обращайтесь на support@cloudpayments.ru
203 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_checkout.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
22 |
23 |
29 |
30 |
37 |
38 |
44 |
45 |
54 |
55 |
65 |
66 |
71 |
72 |
83 |
84 |
95 |
96 |
97 |
107 |
108 |
118 |
119 |
126 |
127 |
132 |
133 |
139 |
140 |
147 |
148 |
149 |
150 |
151 |
161 |
162 |
169 |
170 |
177 |
178 |
179 |
180 |
--------------------------------------------------------------------------------
/sdk/sdk.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | generateDebugSources
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
--------------------------------------------------------------------------------
/sdk/src/main/java/ru/cloudpayments/sdk/cp_card/CPCard.java:
--------------------------------------------------------------------------------
1 | package ru.cloudpayments.sdk.cp_card;
2 |
3 | import android.text.TextUtils;
4 | import android.util.Base64;
5 | import android.util.Log;
6 |
7 | import java.io.UnsupportedEncodingException;
8 | import java.security.InvalidKeyException;
9 | import java.security.KeyFactory;
10 | import java.security.NoSuchAlgorithmException;
11 | import java.security.PublicKey;
12 | import java.security.SecureRandom;
13 | import java.security.spec.InvalidKeySpecException;
14 | import java.security.spec.X509EncodedKeySpec;
15 | import java.text.DateFormat;
16 | import java.text.ParseException;
17 | import java.text.SimpleDateFormat;
18 | import java.util.Calendar;
19 | import java.util.Date;
20 | import java.util.Locale;
21 |
22 | import javax.crypto.BadPaddingException;
23 | import javax.crypto.Cipher;
24 | import javax.crypto.IllegalBlockSizeException;
25 | import javax.crypto.NoSuchPaddingException;
26 |
27 | public class CPCard {
28 |
29 | private String number;
30 | private String expDate;
31 | private String cvv;
32 |
33 | private static final String KEY_VERSION() {
34 | return "04";
35 | }
36 |
37 | private static final String PUBLIC_KEY() {
38 | return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArBZ1NNjvszen6BNWsgyDUJvDUZDtvR4jKNQtEwW1iW7hqJr0TdD8hgTxw3DfH+Hi/7ZjSNdH5EfChvgVW9wtTxrvUXCOyJndReq7qNMo94lHpoSIVW82dp4rcDB4kU+q+ekh5rj9Oj6EReCTuXr3foLLBVpH0/z1vtgcCfQzsLlGkSTwgLqASTUsuzfI8viVUbxE1a+600hN0uBh/CYKoMnCp/EhxV8g7eUmNsWjZyiUrV8AA/5DgZUCB+jqGQT/Dhc8e21tAkQ3qan/jQ5i/QYocA/4jW3WQAldMLj0PA36kINEbuDKq8qRh25v+k4qyjb7Xp4W2DywmNtG3Q20MQIDAQAB";
39 | }
40 |
41 | private CPCard() {
42 | }
43 |
44 | public CPCard(String number) throws IllegalArgumentException {
45 |
46 | if (!isValidNumber(number)) {
47 | throw new IllegalArgumentException("Card number is not correct.");
48 | }
49 |
50 | this.number = number;
51 | }
52 |
53 | public CPCard(String number, String expDate, String cvv) throws IllegalArgumentException {
54 |
55 | if (!isValidNumber(number)) {
56 | throw new IllegalArgumentException("Card number is not correct.");
57 | }
58 |
59 | if (!isValidExpDate(expDate)) {
60 | throw new IllegalArgumentException("Expiration date is not correct.");
61 | }
62 |
63 | this.number = number;
64 | this.expDate = expDate;
65 | this.cvv = cvv;
66 | }
67 |
68 | /**
69 | * @return Тип карты
70 | */
71 | public String getType() {
72 | return getType(number);
73 | }
74 |
75 | /**
76 | * @return Тип карты
77 | */
78 | private String getType(String number) {
79 | return CPCardType.toString(CPCardType.getType(number));
80 | }
81 |
82 | /**
83 | * Валидация номера карты
84 | * @return
85 | */
86 | public boolean isValidNumber() {
87 | return isValidNumber(number);
88 | }
89 |
90 | /**
91 | * Валидация номера карты
92 | * @return
93 | */
94 | public static boolean isValidNumber(String number) {
95 | boolean res = false;
96 | int sum = 0;
97 | int i;
98 | number = prepareCardNumber(number);
99 | if (TextUtils.isEmpty(number)) {
100 | return false;
101 | }
102 | if (number.length() % 2 == 0) {
103 | for (i = 0; i < number.length(); i += 2) {
104 | int c = Integer.parseInt(number.substring(i, i + 1));
105 | c *= 2;
106 | if (c > 9) {
107 | c -= 9;
108 | }
109 | sum += c;
110 | sum += Integer.parseInt(number.substring(i + 1, i + 2));
111 | }
112 | } else {
113 | for (i = 1; i < number.length(); i += 2) {
114 | int c = Integer.parseInt(number.substring(i, i + 1));
115 | c *= 2;
116 | if (c > 9) {
117 | c -= 9;
118 | }
119 | sum += c;
120 | sum += Integer.parseInt(number.substring(i - 1, i));
121 | }
122 | // adding last character
123 | sum += Integer.parseInt(number.substring(i - 1, i));
124 | }
125 | //final check
126 | if (sum % 10 == 0) {
127 | res = true;
128 | }
129 | return res;
130 | }
131 |
132 | /**
133 | * Валидация даты
134 | * @return
135 | */
136 | public boolean isValidExpDate() {
137 | return isValidExpDate(expDate);
138 | }
139 |
140 | /**
141 | * Валидация даты
142 | * @return
143 | */
144 | public static boolean isValidExpDate(String expDate) {
145 | if (expDate.length() != 4) {
146 | return false;
147 | }
148 |
149 | DateFormat format = new SimpleDateFormat("MMyy", Locale.ENGLISH);
150 | format.setLenient(false);
151 | try {
152 | Date date = format.parse(expDate);
153 | Calendar calendar = Calendar.getInstance();
154 | calendar.setTime(date);
155 | calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
156 | date = calendar.getTime();
157 |
158 | Date currentDate = new Date();
159 | if (currentDate.before(date)) {
160 | return true;
161 | } else {
162 | return false;
163 | }
164 | } catch (ParseException e) {
165 | e.printStackTrace();
166 | return false;
167 | }
168 | }
169 |
170 | /**
171 | * Генерим криптограму для карты
172 | * @param publicId
173 | * @return
174 | * @throws UnsupportedEncodingException
175 | * @throws NoSuchPaddingException
176 | * @throws NoSuchAlgorithmException
177 | * @throws BadPaddingException
178 | * @throws IllegalBlockSizeException
179 | * @throws InvalidKeyException
180 | */
181 | public String cardCryptogram(String publicId) throws UnsupportedEncodingException,
182 | NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
183 | IllegalBlockSizeException, InvalidKeyException {
184 | return cardCryptogram(number, expDate, cvv, publicId);
185 | }
186 |
187 | /**
188 | * Генерим криптограму для карты
189 | * @param cardNumber
190 | * @param cardExp
191 | * @param cardCvv
192 | * @param publicId
193 | * @return
194 | * @throws UnsupportedEncodingException
195 | * @throws NoSuchPaddingException
196 | * @throws NoSuchAlgorithmException
197 | * @throws BadPaddingException
198 | * @throws IllegalBlockSizeException
199 | * @throws InvalidKeyException
200 | */
201 | private String cardCryptogram(String cardNumber, String cardExp, String cardCvv, String publicId) throws UnsupportedEncodingException,
202 | NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
203 | IllegalBlockSizeException, InvalidKeyException {
204 |
205 | cardNumber = prepareCardNumber(cardNumber);
206 | String shortNumber = cardNumber.substring(0, 6) + cardNumber.substring(cardNumber.length() - 4, cardNumber.length());
207 | String exp = cardExp.substring(2, 4) + cardExp.substring(0, 2);
208 | String s = cardNumber + "@" + exp + "@" + cardCvv + "@" + publicId;
209 | byte[] bytes = s.getBytes("ASCII");
210 | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
211 | SecureRandom random = new SecureRandom();
212 | cipher.init(Cipher.ENCRYPT_MODE, getRSAKey(), random);
213 | byte[] crypto = cipher.doFinal(bytes);
214 | String crypto64 = "01" +
215 | shortNumber +
216 | exp + KEY_VERSION() +
217 | Base64.encodeToString(crypto, Base64.DEFAULT);
218 | String[] cr_array = crypto64.split("\n");
219 | crypto64 = "";
220 | for (int i = 0; i < cr_array.length; i++) {
221 | crypto64 += cr_array[i];
222 | }
223 | return crypto64;
224 | }
225 |
226 | /**
227 | * Генерим криптограму для CVV
228 | * @param cardCvv
229 | * @return
230 | * @throws UnsupportedEncodingException
231 | * @throws NoSuchPaddingException
232 | * @throws NoSuchAlgorithmException
233 | * @throws BadPaddingException
234 | * @throws IllegalBlockSizeException
235 | * @throws InvalidKeyException
236 | */
237 | public static String cardCryptogramForCVV(String cardCvv) throws UnsupportedEncodingException,
238 | NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
239 | IllegalBlockSizeException, InvalidKeyException {
240 |
241 | byte[] bytes = cardCvv.getBytes("ASCII");
242 | Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
243 | SecureRandom random = new SecureRandom();
244 | cipher.init(Cipher.ENCRYPT_MODE, getRSAKey(), random);
245 | byte[] crypto = cipher.doFinal(bytes);
246 | String crypto64 = "03" +
247 | KEY_VERSION() +
248 | Base64.encodeToString(crypto, Base64.DEFAULT);
249 | String[] cr_array = crypto64.split("\n");
250 | crypto64 = "";
251 | for (int i = 0; i < cr_array.length; i++) {
252 | crypto64 += cr_array[i];
253 | }
254 | return crypto64;
255 | }
256 |
257 | private static String prepareCardNumber(String cardNumber) {
258 | return cardNumber.replaceAll("\\s", "");
259 | }
260 |
261 | private static PublicKey getRSAKey() {
262 | try {
263 | byte[] keyBytes = Base64.decode(PUBLIC_KEY().getBytes("utf-8"), Base64.DEFAULT);
264 | X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
265 | KeyFactory kf;
266 | kf = KeyFactory.getInstance("RSA");
267 | return kf.generatePublic(spec);
268 | } catch (NoSuchAlgorithmException e) {
269 | e.printStackTrace();
270 | return null;
271 | } catch (InvalidKeySpecException e) {
272 | e.printStackTrace();
273 | return null;
274 | } catch (UnsupportedEncodingException e) {
275 | e.printStackTrace();
276 | return null;
277 | }
278 | }
279 | }
280 |
--------------------------------------------------------------------------------