Paytm is a digital payment gateway for accepting online payments. Above all, Paytm has the biggest user base currently in online payment solutions. It provides both online and offline payment solutions. Paytm also provides Payment Gateway which is available for web and mobile platforms. It has a vast variety of payment options like Credit/Debit Card, Net Banking, UPI, International payment, Wallet, etc. In this article, we are going to learn how to integrate Paytm Payment Gateway Integration in a simple eCommerce application. Making eCommerce is a bit complex each and every class can not be covered here So, I have prepared a sample project you can find it frontend and backend.

DEMO

Paytm Payment Gateway Integration in android | loopwiki.com

1. Fashion Shop Application

This application has a limited amount of screens. Application created using design library components like RecyclerView, CardView, etc. To reduce view initialization boilerplate code we are using the butterknife library.

  • Login and Register Screen- Customers can log in or create an account.
  • Fashion Shop Home- This screen lists available products. Here we are creating product data programmatically. You can load products from the server by tweaking a little bit of code. Each product contains a thumbnail, name, price.
  • Fashion Shop Cart- Lists products that are added to the cart. A button to remove products from the cart, and a button to proceed to checkout.
  • Paytm Checkout- This screen is initiated when we start the checkout flow. It will contain all the available payment options.

Below are some screenshots of the Paytm payment flow.

  • Login screen
  • Fashion Shop Home
  • Fashion Shop cart
  • Paytm Payment screen

2. Paytm Payment Lifecycle

Paytm android SDK has very straight forward execution lifecycle.

  1. Preparing Order: When a customer adds products to the cart and goes to the cart screen we calculate the total amount to be paid.
  2. Initiate Paytm Checkout: Once the customer adds products from the cart and clicks the checkout button then Paytm checkout will be initiated. The checkout screen will have different payment options. The customer will choose one of them and completes the payment.
  3. Order Status: Paytm will return the appropriate payment status to the application. The application will handle the status and will show the message accordingly.

3. Paytm Integration

While building applications we need to take care of modern architecture and security measures. This article is made to demonstrate the Paytm payment gateway so I tried to keep the application as minimum as possible to understand it better.

Step 1: Create Account at Paytm.

Step 2: You can activate your account step by step wizard will be presented by Paytm. I am going to use a test account credential for this application.

Step 3: Add dependency for Paytm Android SDK. Below is the latest dependency while creating this article.

  • Add this to project level build.gradle file.
repositories {
        maven {
            url "https://artifactory.paytm.in/libs-release-local"
        }
    }
  • Add this to app level build.gradle file.
    implementation('com.paytm:pgplussdk:1.4.4') { transitive = true; }
Paytm API Key Details

Step 4: Open the dashboard and go to Developer Setting -> API Keys. keep Test Merchant ID and Test Merchant Key handy with you.

4. Fashion Shop Backend

While creating the backend we have to be very cautious about security. I chose Spring to integrate our backend. You can find the backend code here. Below are the endpoints that are defined in the backend.

End PointDescription
account/registerRegister the new customer
account/loginLogin the customer
payment/getCheckSumGenerate checksum
Backend Server Endpoints

5. Paytm Android SDK Integration

1. When the activity launches productFragment will be shown. Customer will select the products.

2. After that customer clicks the cart icon fragment manager will place cartFragment in the main content.

3. When Customer clicks Proceed to Pay button launchPayTMCheckout method gets called.

4. When payment flow starts application will bundle all the Paytm parameters. These bundled parameters will be sent to the payment/getCheckSum endpoint. The server will generate a Hash using the parameters. This hash will be sent to our application as a response.

5. Paytm payment flow will start. Paytm will provide payment options, for example, Credit/Debit Card, UPI, Net Banking, UPI will be presented by Paytm and the customer completes the payment.

6. Paytm will call an appropriate method based on the status of the transaction. After that application will show an appropriate status message.

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.loopwiki.paytmcheckoutexample.API.APIClient;
import com.loopwiki.paytmcheckoutexample.API.APIInterface;
import com.loopwiki.paytmcheckoutexample.Fragment.CartFragment;
import com.loopwiki.paytmcheckoutexample.Model.ChecksumResponse;
import com.loopwiki.paytmcheckoutexample.Model.Product;
import com.loopwiki.paytmcheckoutexample.Fragment.ProductsFragment;
import com.loopwiki.paytmcheckoutexample.R;
import com.loopwiki.paytmcheckoutexample.Model.User;
import com.loopwiki.paytmcheckoutexample.Model.UserDetails;
import com.paytm.pgsdk.PaytmOrder;
import com.paytm.pgsdk.PaytmPGService;
import com.paytm.pgsdk.PaytmPaymentTransactionCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PaymentActivity extends AppCompatActivity implements ProductsFragment.ProductInteractionListener, CartFragment.CartInteractionListener {
    public static final String TAG = PaymentActivity.class.getSimpleName();
    FragmentManager fragmentManager;
    ProductsFragment productsFragment;
    int cartCount = 0;
    @BindView(R.id.textViewCartCount)
    TextView textViewCartCount;
    @BindView(R.id.imageViewCart)
    ImageView imageViewCart;
    List<Product> products;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        productsFragment = ProductsFragment.newInstance();
        products = getProducts();
        productsFragment.products = products;
        fragmentManager.beginTransaction().replace(R.id.main_content, productsFragment).commit();
        imageViewCart.setOnClickListener(v -> {
            CartFragment cartFragment = new CartFragment();
            List<Product> productList = new ArrayList<>();
            for (Product product : products) {
                if (product.isAddedToCart()) {
                    productList.add(product);
                }
            }
            cartFragment.products = productList;
            fragmentManager.beginTransaction().replace(R.id.main_content, cartFragment).addToBackStack(ProductsFragment.TAG).commit();
        });

    }

    // Callback from Products fragment when product is added
    @Override
    public void ProductAddedToCart(Product product) {
        cartCount++;
        textViewCartCount.setVisibility(View.VISIBLE);
        textViewCartCount.setText(String.valueOf(cartCount));
        Toast.makeText(this, getString(R.string.product_added), Toast.LENGTH_SHORT).show();
    }

    // Callback from Products fragment when product is removed
    @Override
    public void ProductRemovedFromCart(Product product) {
        cartCount--;
        textViewCartCount.setText(String.valueOf(cartCount));
        if (cartCount == 0) {
            textViewCartCount.setVisibility(View.GONE);
        }
        Toast.makeText(this, getString(R.string.product_removed), Toast.LENGTH_SHORT).show();
    }

    // method to create dummy product
    private List<Product> getProducts() {
        List<Product> products = new ArrayList<>();
        int[] ImageUrl = {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six};
        String[] Title = {"HRX by Hrithik", "Crew STREET", "Royal Enfield", "Kook N Keech", "ADIDAS", "UNDER ARMOUR"};
        int[] Price = {5000, 2000, 1500, 3000, 1256, 700};
        boolean[] IsNew = {true, false, false, true, true, false};
        for (int i = 0; i < ImageUrl.length; i++) {
            Product product = new Product();
            product.setName(Title[i]);
            product.setImageResourceId(ImageUrl[i]);
            product.setNew(IsNew[i]);
            product.setPrice(Price[i]);
            products.add(product);
        }
        return products;

    }

    // Back button press method
    @Override
    public void onBackPressed() {
        if (fragmentManager.getBackStackEntryCount() == 0) {
            super.onBackPressed();
        } else {
            fragmentManager.popBackStackImmediate();
        }

    }

    // Method called when product is removed from cart
    @Override
    public void RemoveProduct(Product product) {
        int index = this.products.indexOf(product);
        Product ProductToRemove = this.products.get(index);
        ProductToRemove.setAddedToCart(false);
        ProductRemovedFromCart(product);
    }

    // Method is called when we click on Pay button
    @Override
    public void ProceedToPay(int TotalPrice) {
        //launchPayUMoneyFlow(TotalPrice);
        launchPayTMCheckout(TotalPrice);
    }

    // Launch Paytm payment flow
    private void launchPayTMCheckout(int totalPrice) {
        PaytmPGService Service = PaytmPGService.getStagingService("");
        User user = UserDetails.getUser();
        String OrderId = "order" + System.currentTimeMillis();
        // Create map of input parameters
        HashMap<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("MID", getResources().getString(R.string.Merchant_ID));
        paramMap.put("ORDER_ID", OrderId);
        paramMap.put("CUST_ID", user.getUsername());
        paramMap.put("EMAIL", user.getUsername());
        paramMap.put("TXN_AMOUNT", totalPrice + ".00");
        paramMap.put("CHANNEL_ID", "WAP");
        paramMap.put("WEBSITE", "WEBSTAGING");
        // This is the staging value. Production value is available in your dashboard
        paramMap.put("INDUSTRY_TYPE_ID", "Retail");
        // This is the staging value. Production value is available in your dashboard
        paramMap.put("CALLBACK_URL", "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=" + OrderId);

        APIInterface apiInterface = APIClient.getApiInterface();
        // for better security we have to create hash from each of the input parameter.
        // while transferring data this avoid data manipulation
        Call<ChecksumResponse> call = apiInterface.getCheckSum(paramMap);
        call.enqueue(new Callback<ChecksumResponse>() {
            @Override
            public void onResponse(Call<ChecksumResponse> call, Response<ChecksumResponse> response) {
                paramMap.put("CHECKSUMHASH", response.body().getChecksum());
                try {

                    PaytmOrder Order = new PaytmOrder(paramMap);

                    Service.initialize(Order, null);

                    Service.startPaymentTransaction(PaymentActivity.this, true, true, new PaytmPaymentTransactionCallback() {
                        @Override
                        public void onTransactionResponse(Bundle inResponse) {
                            // Paytm payment response
                            Toast.makeText(getApplicationContext(), "Payment Transaction response " + inResponse.toString(), Toast.LENGTH_LONG).show();
                            // Reset the cart
                            clearCart();
                            cartCount = 0;
                            fragmentManager.beginTransaction().replace(R.id.main_content, productsFragment).commit();
                            textViewCartCount.setVisibility(View.GONE);
                        }

                        @Override
                        public void networkNotAvailable() {
                        }

                        @Override
                        public void clientAuthenticationFailed(String inErrorMessage) {
                        }

                        @Override
                        public void someUIErrorOccurred(String inErrorMessage) {
                        }

                        @Override
                        public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {
                        }

                        @Override
                        public void onBackPressedCancelTransaction() {
                        }

                        @Override
                        public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
                        }

                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ChecksumResponse> call, Throwable t) {
                Log.d("error is", t.getStackTrace().toString());
            }
        });
    }

    // method to clear cart
    public void clearCart() {
        for (Product product : products) {
            if (product.isAddedToCart()) {
                product.setAddedToCart(false);
            }
        }
    }
}

6. Testing the Application

After Paytm integration, you can test the application using test card details. Paytm provides test card details which only work with test mode API Key. You can find the latest test details here.

Mobile / username7777777777
OTP489871

7. References

Below are useful links to use while working the project.

  1. Paytm Dashboard
  2. Test API Details
  3. Paytm Documentation

8. Other Links

  1. Android Razorpay Payment Gateway Integration – Ecommerce App.
  2. Android PayU Money Payment Gateway Integration – Ecommerce App.

I hope you understand Paytm android integration. If you still have any queries, please post them in the comments section below, I will be happy to help you.

Author

Hello there, My name is Amardeep founder of loopwiki.com. I have experience in many technologies like Android, Java, Php, etc. In this variety of technologies, I love Android App Development. If you have any idea and you want me to develop for you then let's have chat Conatct

Write A Comment