简体   繁体   English

Android Studio:使用Mercado Pago进行透明结帐

[英]Android Studio: Transparent checkout using Mercado Pago

I am trying to implement for the first time the Mercado Pago's transparent checkout in Android. 我正在尝试首次在Android中实现Mercado Pago的透明结帐。

I've already downloaded the newest version of the SDK provided in https://github.com/mercadopago/px-android and executed it normally in the Emulator. 我已经下载了https://github.com/mercadopago/px-android中提供的SDK的最新版本,并已在Emulator中正常执行。

In the GitHub page mentioned above, we have an explanation of how to implement Mercado Pago's checkout with just one line of code: 在上面提到的GitHub页面上,我们仅用一行代码说明了如何实现Mercado Pago的结帐:

new MercadoPagoCheckout.Builder("public_key", "checkout_preference_id")
    .build()
    .startPayment(activityOrContext, requestCode);

Where public_key we can get in the credentials webpage. public_key我们可以进入凭据网页。 But the String checkout_preference_id I have no idea of how to create it, even though they showed how to create it at the end of the GitHub webpage. 但是,尽管他们在GitHub网页的末尾展示了如何创建它,但是String checkout_preference_id我也不知道如何创建它。

Create your preference id 创建您的偏好ID

curl -X POST \
     'https://api.mercadopago.com/checkout/preferences?access_token=ACCESS_TOKEN' \
     -H 'Content-Type: application/json' \
     -d '{
           "items": [
               {
               "title": "Dummy Item",
               "description": "Multicolor Item",
               "quantity": 1,
               "currency_id": "ARS",
               "unit_price": 10.0
               }
           ],
           "payer": {
               "email": "payer@email.com"
           }
     }'

I tried to put a random String in checkout_preference_id , but it did not work. 我试图在checkout_preference_id放置一个随机String ,但是它不起作用。 Only the String in the example app of Mercado Pago worked. 仅Mercado Pago示例应用程序中的String有效。

private static final String DUMMY_PREFERENCE_ID = "243962506-0bb62e22-5c7b-425e-a0a6-c22d0f4758a9";

All the other ways of implementing it presented in the example app of Mercado Pago require a fake confirmation of payment. Mercado Pago的示例应用程序中介绍的其他所有实现方式都需要伪造的付款确认书。

I appreciate if anyone could show some code of how to create and pass the variable checkout_preference_id into the main command of Mercado Pago payment. 如果有人能展示如何创建并将变量checkout_preference_id传递给Mercado Pago付款的主要命令的代码,我将不胜感激。

EDIT 编辑

I also appreciate if anyone could give us an example of a Not fake confirmation of payment with some code. 如果有人可以给我们提供带有某些代码的非伪造的付款确认示例,我也将不胜感激。

I guess checkout_preference_id can be accessed via a Marketplace website or maybe creating a curl using Android's webservice. 我猜想checkout_preference_id可以通过Marketplace网站访问,也可以使用Android的网络服务来创建curl Then, it is still a mystery to me. 然后,对我来说仍然是一个谜。

Concerning to the alternitive way of paying with MercadoPago, we have this other arguments to pass: 关于使用MercadoPago的替代付款方式,我们还有其他一些论点可以通过:

new MercadoPagoCheckout.Builder("public_key", checkoutPreference, paymentConfiguration)
                .build()
                .startPayment(activityOrContext, requestCode);

Where checkoutPreference allows you to create a custom item to sell. checkoutPreference ,您可以创建要出售的自定义商品

final Item item = new Item.Builder("Product Title", 1, new BigDecimal(12.3)).setDescription("Product Description").build();
CheckoutPreference checkoutPreference = new CheckoutPreference.Builder(Sites.BRASIL, "a@a.a", Collections.singletonList(item)).setDefaultInstallments(1).build();

paymentConfiguration is implemented the fake confirmation of payment . paymentConfiguration实现了假的付款确认

PaymentConfiguration paymentConfiguration = new PaymentConfiguration.Builder(new MyPaymentProcessor()).build();

Where the class MyPaymentProcessor() and the other classes in which it depends on can be found in the GitHub example. 可以在GitHub示例中找到MyPaymentProcessor()MyPaymentProcessor()依赖的其他类的位置。

val queue = Volley.newRequestQueue(this)

    val strJson = "{\n" +
            "           \"items\": [\n" +
            "               {\n" +
            "               \"title\": \"Item\",\n" +
            "               \"description\": \"Multicolor Item\",\n" +
            "               \"quantity\": 1,\n" +
            "               \"currency_id\": \"BRL\",\n" +
            "               \"unit_price\": 35.0\n" +
            "               }\n" +
            "           ],\n" +
            "           \"payer\": {\n" +
            "\t\t    \"name\": \"Núbia\",\n" +
            "\t\t    \"surname\": \"Macedo\",\n" +
            "\t\t    \"email\": \"leann@gmail.com\",\n" +
            "\t\t    \"date_created\": \"2015-06-02T12:58:41.425-04:00\",\n" +
            "\t\t    \"phone\": {\n" +
            "\t\t      \"area_code\": \"\",\n" +
            "\t\t      \"number\": \"880.402.7555\"\n" +
            "\t\t    },\n" +
            "\t\t    \"identification\": {\n" +
            "\t\t      \"type\": \"DNI\",\n" +
            "\t\t      \"number\": \"123456789\"\n" +
            "\t\t    },\n" +
            "\t\t    \"address\": {\n" +
            "\t\t      \"street_name\": \"Núbia Viela\",\n" +
            "\t\t      \"street_number\": 25598,\n" +
            "\t\t      \"zip_code\": \"8972\"\n" +
            "\t\t    }\n" +
            "\t\t  }\n" +
            "     }"

    val obj = JSONObject(strJson)

    //val url = "https://api.mercadopago.com/checkout/preferences"
    val url = "https://api.mercadopago.com/checkout/preferences?access_token=TEST-XXXXXXXXXXXX-XXXXXXX-XXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXX"
    val stringRequest = object : JsonObjectRequest(Method.POST, url, obj,
        Response.Listener<JSONObject> {response ->
            val checkoutPreferenceId: String= response.getString("id")
            MercadoPagoCheckout.Builder("TEST-XXXXXXXX-XXXX-XXXX-XXXXX-XXXXXXXXXX", checkoutPreferenceId)
                .build().startPayment(this, REQUEST_CODE)
        },
        Response.ErrorListener { error ->
            val erros = error.toString()
            val teste1 = "sdsds"
            val teste12 = "sdsds"
            val teste13 = "sdsds"
        }

    ) {
        @Throws(AuthFailureError::class)
        override fun getHeaders(): Map<String, String> {
            val headers = HashMap<String, String>()
            headers["Content-Type"] = "application/json"
            return headers
        }

    }

    val policy = DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
    stringRequest.retryPolicy = policy
    queue.add(stringRequest)

Do not forget to swap your access_token. 不要忘记交换您的access_token。

Json example: https://www.mercadopago.com.br/developers/pt/guides/payments/web-checkout/personalization/ Json示例: https//www.mercadopago.com.br/developers/pt/guides/payments/web-checkout/personalization/

packages: 套餐:

implementation 'com.mercadopago.android.px:checkout:4.5.2'
implementation 'com.android.volley:volley:1.1.0'

Álysson Alexandre helped to understand how to generate the String checkout_preference_id . ÁlyssonAlexandre帮助了解了如何生成字符串 checkout_preference_id

Below you will see the minimum code needed to receive a payment with MercadoPago. 在下面,您将看到通过MercadoPago付款所需的最低代码。

Firstly, you have to add the dependencies in the build.gradle (Module: app) 首先,您必须在build.gradle中添加依赖 (模块:app)

// Dealing with HTTP internet connection
implementation 'com.android.volley:volley:1.1.1'

//Dealing with MercadoPago SDK and dependencies
implementation 'com.mercadopago.android.px:checkout:4.0.+'

Some people recommend to add internet permission in the Manifest 有人建议在清单中添加互联网许可

<uses-permission android:name="android.permission.INTERNET" />

Next, you need to create a JSONObject and there are different ways of doing that. 接下来,您需要创建一个JSONObject,并且有不同的方法。

This way: 这条路:

    StringBuilder strjsonobj = new StringBuilder();
    String strJson = "{\n" +
            "           \"items\": [\n" +
            "               {\n" +
            "               \"title\": \"Item\",\n" +
            "               \"description\": \"Multicolor Item\",\n" +
            "               \"quantity\": 1,\n" +
            "               \"currency_id\": \"BRL\",\n" +
            "               \"unit_price\": 35.0\n" +
            "               }\n" +
            "           ],\n" +
            "           \"payer\": {\n" +
            "\t\t    \"name\": \"Núbia\",\n" +
            "\t\t    \"surname\": \"Macedo\",\n" +
            "\t\t    \"email\": \"leann@gmail.com\",\n" +
            "\t\t    \"date_created\": \"2015-06-02T12:58:41.425-04:00\",\n" +
            "\t\t    \"phone\": {\n" +
            "\t\t      \"area_code\": \"\",\n" +
            "\t\t      \"number\": \"880.402.7555\"\n" +
            "\t\t    },\n" +
            "\t\t    \"identification\": {\n" +
            "\t\t      \"type\": \"DNI\",\n" +
            "\t\t      \"number\": \"123456789\"\n" +
            "\t\t    },\n" +
            "\t\t    \"address\": {\n" +
            "\t\t      \"street_name\": \"Núbia Viela\",\n" +
            "\t\t      \"street_number\": 25598,\n" +
            "\t\t      \"zip_code\": \"8972\"\n" +
            "\t\t    }\n" +
            "\t\t  }\n" +
            "     }";

    strjsonobj.append(strJson);
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(strjsonobj.toString());
        Log.i("debinf MainAct", "object is : "+jsonObject);
    } catch (JSONException e) {
        e.printStackTrace();
    }

Or this way: 或者这样:

    JSONObject jsonObject = new JSONObject();
    final JSONObject itemJSON = new JSONObject();
    final JSONObject payerJSON = new JSONObject();
    JSONArray itemJsonArray = new JSONArray();
    try {

        itemJSON.put("title", "Dummy Item");
        itemJSON.put("description", "Multicolor Item");
        itemJSON.put("quantity", 1);
        itemJSON.put("currency_id", "BRL");
        itemJSON.put("unit_price", 2.10);

        itemJsonArray.put(itemJSON);

        JSONObject phoneJSON = new JSONObject();
        phoneJSON.put("area_code", "");
        phoneJSON.put("number", "880.402.7555");
        JSONObject idJSON = new JSONObject();
        idJSON.put("type", "DNI");
        idJSON.put("number", "123456789");
        JSONObject addressJSON = new JSONObject();
        addressJSON.put("street_name", "Núbia Viela");
        addressJSON.put("street_number", 25598);
        addressJSON.put("zip_code", "8972");

        payerJSON.put("name", "Núbia");
        payerJSON.put("surname", "Macedo");
        payerJSON.put("email", "leann@gmail.com");
        payerJSON.put("date_created", "2015-06-02T12:58:41.425-04:00");
        payerJSON.put("phone", phoneJSON);
        payerJSON.put("identification", idJSON);
        payerJSON.put("address", addressJSON);


        jsonObject.put("items", itemJsonArray);
        jsonObject.put("payer", payerJSON);
    } catch (JSONException e) {
        e.printStackTrace();
    }

MercadoPago suggests to send as much information as you can about the payer in order to increase the rate of payment conversion. MercadoPago建议您发送有关付款人的尽可能多的信息,以提高付款转换率。 But you can send as little as shown in the question. 但是您可以按照问题所示发送尽可能少的内容。

Besides that, you can personalize other things in the JSONObject such as shown here 除此之外,您还可以个性化JSONObject中的其他内容,例如此处所示

Now, let's create the variable String checkout_preference_id . 现在,让我们创建变量String checkout_preference_id For that, I used the method volley . 为此,我使用了volley方法。 When the MercadoPago server sends back our variable, we will automatically start the payment. 当MercadoPago服务器发回我们的变量时,我们将自动开始付款。

    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    final String url = "https://api.mercadopago.com/checkout/preferences?access_token="+ACCESS_TOKEN_SANDBOX;
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                Log.i("debinf MainAct", "response JSONObject: "+response);
                String checkoutPreferenceId = response.getString("id");
                new MercadoPagoCheckout.Builder(PUBLIC_KEY_SANDBOX, checkoutPreferenceId).build().startPayment(MainActivity.this,REQUEST_CODE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("debinf MainAct", "response ERROR: "+error.networkResponse.allHeaders);
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };
    requestQueue.add(jsonObjectRequest);

Use REQUEST_CODE sent by startPayment to obtain the checkout result in onActivityResult . 使用startPayment发送的REQUEST_CODEonActivityResult中获取结帐结果。

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (requestCode == REQUEST_CODE) {
        if (resultCode == MercadoPagoCheckout.PAYMENT_RESULT_CODE) {
            final Payment payment = (Payment) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_PAYMENT_RESULT);
            ((TextView) findViewById(R.id.mp_results)).setText("Resultado del pago: " + payment.getStatus());
            //Done!
        } else if (resultCode == RESULT_CANCELED) {
            if (data != null && data.getExtras() != null
                && data.getExtras().containsKey(MercadoPagoCheckout.EXTRA_ERROR)) {
                final MercadoPagoError mercadoPagoError =
                    (MercadoPagoError) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_ERROR);
                ((TextView) findViewById(R.id.mp_results)).setText("Error: " +  mercadoPagoError.getMessage());
                //Resolve error in checkout
            } else {
                //Resolve canceled checkout
            }
        }
    }
}

That's it! 而已! Please, be free to improve the above code. 请随意改进上面的代码。 Mainly, regarding to the security issues. 主要是关于安全问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM