PAYUMONEY INTEGRATION ANDROID
Add this to build level:
Add this to build level:
implementation 'com.payumoney.sdkui:plug-n-play:1.5.0'
Create a class:public enum AppEnvironment { SANDBOX { @Override public String merchant_Key() { return "QylhKRVd"; } @Override public String merchant_ID() { return "5960507"; } @Override public String furl() { return "https://www.payumoney.com/mobileapp/payumoney/failure.php"; } @Override public String surl() { return "https://www.payumoney.com/mobileapp/payumoney/success.php"; } @Override public String salt() { return "seVTUgzrgE"; } @Override public boolean debug() { return true; } }, PRODUCTION { @Override public String merchant_Key() { return "QylhKRVd"; } @Override public String merchant_ID() { return "5960507"; } @Override public String furl() { return "https://www.payumoney.com/mobileapp/payumoney/failure.php"; } @Override public String surl() { return "https://www.payumoney.com/mobileapp/payumoney/success.php"; } @Override public String salt() { return "seVTUgzrgE"; } @Override public boolean debug() { return false; } }; public abstract String merchant_Key(); public abstract String merchant_ID(); public abstract String furl(); public abstract String surl(); public abstract String salt(); public abstract boolean debug(); }
Second Step to create another class:
public class AppPreference { private String dummyAmount = "10";//"10"; private String dummyEmail = "xyz@gmail.com";//"";//d.basak.db@gmail.com private String productInfo ="product_info";// "product_info"; private String firstName = "firstname"; //"firstname"; private boolean isOverrideResultScreen = true; public static final String USER_EMAIL = "user_email"; public static final String USER_MOBILE = "user_mobile"; public static final String PHONE_PATTERN = "^[987]\\d{9}$"; public static final long MENU_DELAY = 300; public static String USER_DETAILS = "user_details"; public static int selectedTheme = -1; private boolean isDisableWallet, isDisableSavedCards, isDisableNetBanking, isDisableThirdPartyWallets, isDisableExitConfirmation; boolean isDisableWallet() { return isDisableWallet; } void setDisableWallet(boolean disableWallet) { isDisableWallet = disableWallet; } boolean isDisableSavedCards() { return isDisableSavedCards; } void setDisableSavedCards(boolean disableSavedCards) { isDisableSavedCards = disableSavedCards; } boolean isDisableNetBanking() { return isDisableNetBanking; } void setDisableNetBanking(boolean disableNetBanking) { isDisableNetBanking = disableNetBanking; } boolean isDisableThirdPartyWallets() { return isDisableThirdPartyWallets; } void setDisableThirdPartyWallets(boolean disableThirdPartyWallets) { isDisableThirdPartyWallets = disableThirdPartyWallets; } boolean isDisableExitConfirmation() { return isDisableExitConfirmation; } void setDisableExitConfirmation(boolean disableExitConfirmation) { isDisableExitConfirmation = disableExitConfirmation; } public String getDummyAmount() { return dummyAmount; } public void setDummyAmount(String dummyAmount) { this.dummyAmount = dummyAmount; } public String getDummyEmail() { return dummyEmail; } public void setDummyEmail(String dummyEmail) { this.dummyEmail = dummyEmail; } public boolean isOverrideResultScreen() { return isOverrideResultScreen; } public void setOverrideResultScreen(boolean overrideResultScreen) { isOverrideResultScreen = overrideResultScreen; } public String getProductInfo() { return productInfo; } public void setProductInfo(String productInfo) { this.productInfo = productInfo; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } }3rd Step :public abstract class BaseActivity extends AppCompatActivity { public Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutResource()); toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setLogo(R.drawable.app_logo); toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.light_white)); } } protected abstract int getLayoutResource(); protected void setActionBarIcon(int iconRes) { toolbar.setNavigationIcon(iconRes); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }4th Step :public class BaseApplication extends Application { AppEnvironment appEnvironment; @Override public void onCreate() { super.onCreate(); appEnvironment = AppEnvironment.SANDBOX; } public AppEnvironment getAppEnvironment() { return appEnvironment; } public void setAppEnvironment(AppEnvironment appEnvironment) { this.appEnvironment = appEnvironment; } }5th Step:import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.annotation.IdRes; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.AppCompatRadioButton; import android.support.v7.widget.SwitchCompat; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.payumoney.core.PayUmoneyConfig; import com.payumoney.core.PayUmoneyConstants; import com.payumoney.core.PayUmoneySdkInitializer; import com.payumoney.core.entity.TransactionResponse; import com.payumoney.sdkui.ui.utils.PayUmoneyFlowManager; import com.payumoney.sdkui.ui.utils.ResultModel; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; //import com.payumoney.sdkui.ui.utils.PPConfig; public class MainActivity extends BaseActivity implements View.OnClickListener { public static final String TAG = "MainActivity : "; private boolean isDisableExitConfirmation = false; private String userMobile, userEmail; private SharedPreferences settings; private SharedPreferences.Editor editor; private SharedPreferences userDetailsPreference; private EditText email_et, mobile_et, amount_et; private TextInputLayout email_til, mobile_til; private RadioGroup radioGroup_color_theme, radioGroup_select_env; private SwitchCompat switch_disable_wallet, switch_disable_netBanks, switch_disable_cards, switch_disable_ThirdPartyWallets, switch_disable_ExitConfirmation; private TextView logoutBtn; private AppCompatRadioButton radio_btn_default; private AppPreference mAppPreference; private AppCompatRadioButton radio_btn_theme_purple, radio_btn_theme_pink, radio_btn_theme_green, radio_btn_theme_grey; private Button payNowButton; private PayUmoneySdkInitializer.PaymentParam mPaymentParams; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAppPreference = new AppPreference(); Toolbar toolbar = (Toolbar) findViewById(R.id.custom_toolbar); setSupportActionBar(toolbar); toolbar.setTitleTextColor(Color.WHITE); toolbar.setTitle(getString(R.string.app_name)); settings = getSharedPreferences("settings", MODE_PRIVATE); logoutBtn = (TextView) findViewById(R.id.logout_button); email_et = (EditText) findViewById(R.id.email_et); mobile_et = (EditText) findViewById(R.id.mobile_et); amount_et = (EditText) findViewById(R.id.amount_et); amount_et.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(7, 2)}); email_til = (TextInputLayout) findViewById(R.id.email_til); mobile_til = (TextInputLayout) findViewById(R.id.mobile_til); radioGroup_color_theme = (RadioGroup) findViewById(R.id.radio_grp_color_theme); radio_btn_default = (AppCompatRadioButton) findViewById(R.id.radio_btn_theme_default); radio_btn_theme_pink = (AppCompatRadioButton) findViewById(R.id.radio_btn_theme_pink); radio_btn_theme_purple = (AppCompatRadioButton) findViewById(R.id.radio_btn_theme_purple); radio_btn_theme_green = (AppCompatRadioButton) findViewById(R.id.radio_btn_theme_green); radio_btn_theme_grey = (AppCompatRadioButton) findViewById(R.id.radio_btn_theme_grey); if (PayUmoneyFlowManager.isUserLoggedIn(getApplicationContext())) { logoutBtn.setVisibility(View.VISIBLE); } else { logoutBtn.setVisibility(View.GONE); } logoutBtn.setOnClickListener(this); AppCompatRadioButton radio_btn_sandbox = (AppCompatRadioButton) findViewById(R.id.radio_btn_sandbox); AppCompatRadioButton radio_btn_production = (AppCompatRadioButton) findViewById(R.id.radio_btn_production); radioGroup_select_env = (RadioGroup) findViewById(R.id.radio_grp_env); payNowButton = (Button) findViewById(R.id.pay_now_button); payNowButton.setOnClickListener(this); initListeners(); //Set Up SharedPref setUpUserDetails(); if (settings.getBoolean("is_prod_env", false)) { ((BaseApplication) getApplication()).setAppEnvironment(AppEnvironment.PRODUCTION); radio_btn_production.setChecked(true); } else { ((BaseApplication) getApplication()).setAppEnvironment(AppEnvironment.SANDBOX); radio_btn_sandbox.setChecked(true); } setupCitrusConfigs(); } public static String hashCal(String str) { byte[] hashseq = str.getBytes(); StringBuilder hexString = new StringBuilder(); try { MessageDigest algorithm = MessageDigest.getInstance("SHA-512"); algorithm.reset(); algorithm.update(hashseq); byte messageDigest[] = algorithm.digest(); for (byte aMessageDigest : messageDigest) { String hex = Integer.toHexString(0xFF & aMessageDigest); if (hex.length() == 1) { hexString.append("0"); } hexString.append(hex); } } catch (NoSuchAlgorithmException ignored) { } return hexString.toString(); } public static void setErrorInputLayout(EditText editText, String msg, TextInputLayout textInputLayout) { textInputLayout.setError(msg); editText.requestFocus(); } public static boolean isValidEmail(String strEmail) { return strEmail != null && android.util.Patterns.EMAIL_ADDRESS.matcher(strEmail).matches(); } public static boolean isValidPhone(String phone) { Pattern pattern = Pattern.compile(AppPreference.PHONE_PATTERN); Matcher matcher = pattern.matcher(phone); return matcher.matches(); } private void setUpUserDetails() { userDetailsPreference = getSharedPreferences(AppPreference.USER_DETAILS, MODE_PRIVATE); userEmail = userDetailsPreference.getString(AppPreference.USER_EMAIL, mAppPreference.getDummyEmail()); userMobile = userDetailsPreference.getString(AppPreference.USER_MOBILE, ""); email_et.setText(userEmail); mobile_et.setText(userMobile); amount_et.setText(mAppPreference.getDummyAmount()); restoreAppPref(); } private void restoreAppPref() { //Set Up saved theme pref switch (AppPreference.selectedTheme) { case -1: radio_btn_default.setChecked(true); break; case R.style.AppTheme_pink: radio_btn_theme_pink.setChecked(true); break; case R.style.AppTheme_Grey: radio_btn_theme_grey.setChecked(true); break; case R.style.AppTheme_purple: radio_btn_theme_purple.setChecked(true); break; case R.style.AppTheme_Green: radio_btn_theme_green.setChecked(true); break; default: radio_btn_default.setChecked(true); break; } } @Override protected void onResume() { super.onResume(); payNowButton.setEnabled(true); if (PayUmoneyFlowManager.isUserLoggedIn(getApplicationContext())) { logoutBtn.setVisibility(View.VISIBLE); } else { logoutBtn.setVisibility(View.GONE); } } /** * This function sets the mode to PRODUCTION in Shared Preference */ private void selectProdEnv() { new Handler(getMainLooper()).postDelayed(new Runnable() { @Override public void run() { ((BaseApplication) getApplication()).setAppEnvironment(AppEnvironment.PRODUCTION); editor = settings.edit(); editor.putBoolean("is_prod_env", true); editor.apply(); if (PayUmoneyFlowManager.isUserLoggedIn(getApplicationContext())) { logoutBtn.setVisibility(View.VISIBLE); } else { logoutBtn.setVisibility(View.GONE); } setupCitrusConfigs(); } }, AppPreference.MENU_DELAY); } /** * This function sets the mode to SANDBOX in Shared Preference */ private void selectSandBoxEnv() { ((BaseApplication) getApplication()).setAppEnvironment(AppEnvironment.SANDBOX); editor = settings.edit(); editor.putBoolean("is_prod_env", false); editor.apply(); if (PayUmoneyFlowManager.isUserLoggedIn(getApplicationContext())) { logoutBtn.setVisibility(View.VISIBLE); } else { logoutBtn.setVisibility(View.GONE); } setupCitrusConfigs(); } private void setupCitrusConfigs() { AppEnvironment appEnvironment = ((BaseApplication) getApplication()).getAppEnvironment(); if (appEnvironment == AppEnvironment.PRODUCTION) { Toast.makeText(MainActivity.this, "Environment Set to Production", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Environment Set to SandBox", Toast.LENGTH_SHORT).show(); } } /** * This function sets the layout for activity */ @Override protected int getLayoutResource() { return R.layout.activity_main; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result Code is -1 send from Payumoney activity Log.d("MainActivity", "request code " + requestCode + " resultcode " + resultCode); if (requestCode == PayUmoneyFlowManager.REQUEST_CODE_PAYMENT && resultCode == RESULT_OK && data != null) { TransactionResponse transactionResponse = data.getParcelableExtra(PayUmoneyFlowManager .INTENT_EXTRA_TRANSACTION_RESPONSE); ResultModel resultModel = data.getParcelableExtra(PayUmoneyFlowManager.ARG_RESULT); // Check which object is non-null if (transactionResponse != null && transactionResponse.getPayuResponse() != null) { if (transactionResponse.getTransactionStatus().equals(TransactionResponse.TransactionStatus.SUCCESSFUL)) { //Success Transaction } else { //Failure Transaction } // Response from Payumoney String payuResponse = transactionResponse.getPayuResponse(); // Response from SURl and FURL String merchantResponse = transactionResponse.getTransactionDetails(); new AlertDialog.Builder(this) .setCancelable(false) .setMessage("Payu's Data : " + payuResponse + "\n\n\n Merchant's Data: " + merchantResponse) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } else if (resultModel != null && resultModel.getError() != null) { Log.d(TAG, "Error response : " + resultModel.getError().getTransactionResponse()); } else { Log.d(TAG, "Both objects are null!"); } } } @Override public void onClick(View v) { userEmail = email_et.getText().toString().trim(); userMobile = mobile_et.getText().toString().trim(); if (v.getId() == R.id.logout_button || validateDetails(userEmail, userMobile)) { switch (v.getId()) { case R.id.pay_now_button: payNowButton.setEnabled(false); launchPayUMoneyFlow(); break; case R.id.logout_button: PayUmoneyFlowManager.logoutUser(getApplicationContext()); logoutBtn.setVisibility(View.GONE); break; } } } private void initListeners() { email_et.addTextChangedListener(new EditTextInputWatcher(email_til)); mobile_et.addTextChangedListener(new EditTextInputWatcher(mobile_til)); radioGroup_color_theme.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) { mAppPreference.setOverrideResultScreen(true); switch (i) { case R.id.radio_btn_theme_default: AppPreference.selectedTheme = -1; break; case R.id.radio_btn_theme_pink: AppPreference.selectedTheme = R.style.AppTheme_pink; break; case R.id.radio_btn_theme_grey: AppPreference.selectedTheme = R.style.AppTheme_Grey; break; case R.id.radio_btn_theme_purple: AppPreference.selectedTheme = R.style.AppTheme_purple; break; case R.id.radio_btn_theme_green: AppPreference.selectedTheme = R.style.AppTheme_Green; break; default: AppPreference.selectedTheme = -1; break; } } }); radioGroup_select_env.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) { switch (i) { case R.id.radio_btn_sandbox: selectSandBoxEnv(); break; case R.id.radio_btn_production: selectProdEnv(); break; default: selectSandBoxEnv(); break; } } }); } /** * This fucntion checks if email and mobile number are valid or not. * * @param email email id entered in edit text * @param mobile mobile number entered in edit text * @return boolean value */ public boolean validateDetails(String email, String mobile) { email = email.trim(); mobile = mobile.trim(); if (TextUtils.isEmpty(mobile)) { setErrorInputLayout(mobile_et, getString(R.string.err_phone_empty), mobile_til); return false; } else if (!isValidPhone(mobile)) { setErrorInputLayout(mobile_et, getString(R.string.err_phone_not_valid), mobile_til); return false; } else if (TextUtils.isEmpty(email)) { setErrorInputLayout(email_et, getString(R.string.err_email_empty), email_til); return false; } else if (!isValidEmail(email)) { setErrorInputLayout(email_et, getString(R.string.email_not_valid), email_til); return false; } else { return true; } } /** * This function prepares the data for payment and launches payumoney plug n play sdk */ private void launchPayUMoneyFlow() { PayUmoneyConfig payUmoneyConfig = PayUmoneyConfig.getInstance(); //Use this to set your custom text on result screen button payUmoneyConfig.setDoneButtonText(((EditText) findViewById(R.id.status_page_et)).getText().toString()); //Use this to set your custom title for the activity payUmoneyConfig.setPayUmoneyActivityTitle(((EditText) findViewById(R.id.activity_title_et)).getText().toString()); payUmoneyConfig.disableExitConfirmation(isDisableExitConfirmation); PayUmoneySdkInitializer.PaymentParam.Builder builder = new PayUmoneySdkInitializer.PaymentParam.Builder(); double amount = 0; try { amount = Double.parseDouble(amount_et.getText().toString()); } catch (Exception e) { e.printStackTrace(); } String txnId = System.currentTimeMillis() + ""; //String txnId = "TXNID720431525261327973"; String phone = mobile_til.getEditText().getText().toString().trim(); String productName = mAppPreference.getProductInfo(); String firstName = mAppPreference.getFirstName(); String email = email_til.getEditText().getText().toString().trim(); String udf1 = ""; String udf2 = ""; String udf3 = ""; String udf4 = ""; String udf5 = ""; String udf6 = ""; String udf7 = ""; String udf8 = ""; String udf9 = ""; String udf10 = ""; AppEnvironment appEnvironment = ((BaseApplication) getApplication()).getAppEnvironment(); builder.setAmount(String.valueOf(amount)) .setTxnId(txnId) .setPhone(phone) .setProductName(productName) .setFirstName(firstName) .setEmail(email) .setsUrl(appEnvironment.surl()) .setfUrl(appEnvironment.furl()) .setUdf1(udf1) .setUdf2(udf2) .setUdf3(udf3) .setUdf4(udf4) .setUdf5(udf5) .setUdf6(udf6) .setUdf7(udf7) .setUdf8(udf8) .setUdf9(udf9) .setUdf10(udf10) .setIsDebug(appEnvironment.debug()) .setKey(appEnvironment.merchant_Key()) .setMerchantId(appEnvironment.merchant_ID()); try { mPaymentParams = builder.build(); /* * Hash should always be generated from your server side. * */ // generateHashFromServer(mPaymentParams); /* *//** * Do not use below code when going live * Below code is provided to generate hash from sdk. * It is recommended to generate hash from server side only. * */ mPaymentParams = calculateServerSideHashAndInitiatePayment1(mPaymentParams); if (AppPreference.selectedTheme != -1) { PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams,MainActivity.this, AppPreference.selectedTheme,mAppPreference.isOverrideResultScreen()); } else { PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams,MainActivity.this, R.style.AppTheme_default, mAppPreference.isOverrideResultScreen()); } } catch (Exception e) { // some exception occurred Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); payNowButton.setEnabled(true); } } /** * Thus function calculates the hash for transaction * * @param paymentParam payment params of transaction * @return payment params along with calculated merchant hash */ private PayUmoneySdkInitializer.PaymentParam calculateServerSideHashAndInitiatePayment1(final PayUmoneySdkInitializer.PaymentParam paymentParam) { StringBuilder stringBuilder = new StringBuilder(); HashMap<String, String> params = paymentParam.getParams(); stringBuilder.append(params.get(PayUmoneyConstants.KEY) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.TXNID) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.AMOUNT) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.PRODUCT_INFO) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.FIRSTNAME) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.EMAIL) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.UDF1) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.UDF2) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.UDF3) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.UDF4) + "|"); stringBuilder.append(params.get(PayUmoneyConstants.UDF5) + "||||||"); AppEnvironment appEnvironment = ((BaseApplication) getApplication()).getAppEnvironment(); stringBuilder.append(appEnvironment.salt()); String hash = hashCal(stringBuilder.toString()); paymentParam.setMerchantHash(hash); return paymentParam; } /** * This method generates hash from server. * * @param paymentParam payments params used for hash generation */ public void generateHashFromServer(PayUmoneySdkInitializer.PaymentParam paymentParam) { //nextButton.setEnabled(false); // lets not allow the user to click the button again and again. HashMap<String, String> params = paymentParam.getParams(); // lets create the post params StringBuffer postParamsBuffer = new StringBuffer(); postParamsBuffer.append(concatParams(PayUmoneyConstants.KEY, params.get(PayUmoneyConstants.KEY))); postParamsBuffer.append(concatParams(PayUmoneyConstants.AMOUNT, params.get(PayUmoneyConstants.AMOUNT))); postParamsBuffer.append(concatParams(PayUmoneyConstants.TXNID, params.get(PayUmoneyConstants.TXNID))); postParamsBuffer.append(concatParams(PayUmoneyConstants.EMAIL, params.get(PayUmoneyConstants.EMAIL))); postParamsBuffer.append(concatParams("productinfo", params.get(PayUmoneyConstants.PRODUCT_INFO))); postParamsBuffer.append(concatParams("firstname", params.get(PayUmoneyConstants.FIRSTNAME))); postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF1, params.get(PayUmoneyConstants.UDF1))); postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF2, params.get(PayUmoneyConstants.UDF2))); postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF3, params.get(PayUmoneyConstants.UDF3))); postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF4, params.get(PayUmoneyConstants.UDF4))); postParamsBuffer.append(concatParams(PayUmoneyConstants.UDF5, params.get(PayUmoneyConstants.UDF5))); String postParams = postParamsBuffer.charAt(postParamsBuffer.length() - 1) == '&' ? postParamsBuffer.substring(0, postParamsBuffer.length() - 1).toString() : postParamsBuffer.toString(); // lets make an api call GetHashesFromServerTask getHashesFromServerTask = new GetHashesFromServerTask(); getHashesFromServerTask.execute(postParams); } protected String concatParams(String key, String value) { return key + "=" + value + "&"; } /** * This AsyncTask generates hash from server. */ private class GetHashesFromServerTask extends AsyncTask<String, String, String> { private ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Please wait..."); progressDialog.show(); } @Override protected String doInBackground(String... postParams) { String merchantHash = ""; try { //TODO Below url is just for testing purpose, merchant needs to replace this with their server side hash generation url URL url = new URL("https://payu.herokuapp.com/get_hash"); String postParam = postParams[0]; byte[] postParamsByte = postParam.getBytes("UTF-8"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(postParamsByte.length)); conn.setDoOutput(true); conn.getOutputStream().write(postParamsByte); InputStream responseInputStream = conn.getInputStream(); StringBuffer responseStringBuffer = new StringBuffer(); byte[] byteContainer = new byte[1024]; for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) { responseStringBuffer.append(new String(byteContainer, 0, i)); } JSONObject response = new JSONObject(responseStringBuffer.toString()); Iterator<String> payuHashIterator = response.keys(); while (payuHashIterator.hasNext()) { String key = payuHashIterator.next(); switch (key) { /** * This hash is mandatory and needs to be generated from merchant's server side * */ case "payment_hash": merchantHash = response.getString(key); break; default: break; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return merchantHash; } @Override protected void onPostExecute(String merchantHash) { super.onPostExecute(merchantHash); progressDialog.dismiss(); payNowButton.setEnabled(true); if (merchantHash.isEmpty() || merchantHash.equals("")) { Toast.makeText(MainActivity.this, "Could not generate hash", Toast.LENGTH_SHORT).show(); } else { mPaymentParams.setMerchantHash(merchantHash); if (AppPreference.selectedTheme != -1) { PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams, MainActivity.this, AppPreference.selectedTheme, mAppPreference.isOverrideResultScreen()); } else { PayUmoneyFlowManager.startPayUMoneyFlow(mPaymentParams, MainActivity.this, R.style.AppTheme_default, mAppPreference.isOverrideResultScreen()); } } } } public static class EditTextInputWatcher implements TextWatcher { private TextInputLayout textInputLayout; EditTextInputWatcher(TextInputLayout textInputLayout) { this.textInputLayout = textInputLayout; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.toString().length() > 0) { textInputLayout.setError(null); textInputLayout.setErrorEnabled(false); } } } public class DecimalDigitsInputFilter implements InputFilter { Pattern mPattern; public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) { mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?"); } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { Matcher matcher = mPattern.matcher(dest); if (!matcher.matches()) return ""; return null; } } }CREATE XML LAYOUT:activity_main:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/lib-auto" xmlns:card_view="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:orientation="vertical" tools:context="com.rahulhooda.integrationsampleapp_payumoneypnp.FinalCode.MainActivity"> <android.support.v7.widget.Toolbar android:id="@+id/custom_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/dimen_5dp" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/dimen_5dp"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginLeft="@dimen/dimen_10dp" android:layout_marginRight="@dimen/dimen_10dp" android:padding="@dimen/dimen_10dp" app:cardBackgroundColor="@color/light_white" app:cardCornerRadius="@dimen/dimen_3dp" app:cardElevation="@dimen/dimen_5dp" app:cardPreventCornerOverlap="false" app:contentPaddingBottom="@dimen/dimen_10dp" app:contentPaddingLeft="@dimen/dimen_15dp" app:contentPaddingRight="@dimen/dimen_15dp" app:contentPaddingTop="@dimen/dimen_10dp" card_view:cardElevation="@dimen/dimen_5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select Environment" android:textColor="@color/payumoney_black" android:textSize="@dimen/dimen_18sp" /> <RadioGroup android:id="@+id/radio_grp_env" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/dimen_5dp" android:orientation="horizontal" android:paddingLeft="@dimen/dimen_5dp" android:paddingRight="@dimen/dimen_5dp"> <android.support.v7.widget.AppCompatRadioButton android:id="@+id/radio_btn_sandbox" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="@integer/int_1" android:text="Sandbox" android:textColor="@color/payumoney_black" /> <android.support.v7.widget.AppCompatRadioButton android:id="@+id/radio_btn_production" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="@integer/int_1" android:checked="true" android:text="Production" /> </RadioGroup> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginLeft="@dimen/dimen_10dp" android:layout_marginRight="@dimen/dimen_10dp" android:layout_marginTop="@dimen/dimen_10dp" android:padding="@dimen/dimen_10dp" app:cardBackgroundColor="@color/light_white" app:cardCornerRadius="@dimen/dimen_3dp" app:cardElevation="@dimen/dimen_5dp" app:cardPreventCornerOverlap="false" app:contentPaddingBottom="@dimen/dimen_5dp" app:contentPaddingLeft="@dimen/dimen_15dp" app:contentPaddingRight="@dimen/dimen_15dp" app:contentPaddingTop="@dimen/dimen_5dp" card_view:cardElevation="@dimen/dimen_5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter User details" android:textColor="@color/payumoney_black" android:textSize="@dimen/dimen_18sp" /> <android.support.design.widget.TextInputLayout android:id="@+id/email_til" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/dimen_10dp" app:errorEnabled="false"> <EditText android:id="@+id/email_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:hint="Enter email" android:imeOptions="actionNext" android:inputType="textEmailAddress" android:maxLines="1" android:nextFocusDown="@+id/card_name_et" android:textColor="@color/payumoney_black" android:textSize="16sp" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/mobile_til" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEnabled="false"> <EditText android:id="@+id/mobile_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:hint="Enter mobile" android:imeOptions="actionDone" android:inputType="phone" android:maxLength="10" android:maxLines="1" android:nextFocusDown="@+id/card_name_et" android:textColor="@color/payumoney_black" android:textSize="16sp" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/amount_til" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEnabled="false"> <EditText android:id="@+id/amount_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:hint="Enter amount" android:imeOptions="actionNext" android:inputType="numberDecimal" android:maxLines="1" android:textColor="@color/payumoney_black" android:textSize="16sp" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/activity_title_til" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEnabled="false"> <EditText android:id="@+id/activity_title_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:hint="Activity title" android:imeOptions="actionNext" android:maxLines="1" android:textColor="@color/payumoney_black" android:textSize="16sp" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/status_page_til" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEnabled="false"> <EditText android:id="@+id/status_page_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:hint="Status page text" android:imeOptions="actionNext" android:maxLines="1" android:textColor="@color/payumoney_black" android:textSize="16sp" /> </android.support.design.widget.TextInputLayout> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/dimen_10dp" android:layout_marginRight="@dimen/dimen_10dp" android:layout_marginTop="@dimen/dimen_10dp" android:padding="@dimen/dimen_10dp" app:cardBackgroundColor="@color/light_white" app:cardCornerRadius="@dimen/dimen_3dp" app:cardElevation="@dimen/dimen_5dp" app:cardPreventCornerOverlap="false" app:contentPaddingBottom="@dimen/dimen_10dp" app:contentPaddingLeft="@dimen/dimen_5dp" app:contentPaddingRight="@dimen/dimen_5dp" app:contentPaddingTop="@dimen/dimen_10dp" card_view:cardElevation="@dimen/dimen_5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/dimen_5dp" android:text="Select color theme" android:textColor="@color/payumoney_black" android:textSize="@dimen/dimen_18sp" /> <RadioGroup android:id="@+id/radio_grp_color_theme" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/dimen_10dp" android:orientation="horizontal" android:paddingLeft="@dimen/dimen_5dp" android:paddingRight="@dimen/dimen_5dp"> <android.support.v7.widget.AppCompatRadioButton android:id="@+id/radio_btn_theme_default" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="@integer/int_1" android:button="@null" android:checked="true" android:drawableTop="?android:attr/listChoiceIndicatorSingle" android:gravity="center_horizontal|bottom" android:text="Default" android:textColor="@color/orange_accent" android:textStyle="bold" android:theme="@style/ThemeRadioButton.Default" /> <android.support.v7.widget.AppCompatRadioButton android:id="@+id/radio_btn_theme_pink" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="@integer/int_1" android:button="@null" android:drawableTop="?android:attr/listChoiceIndicatorSingle" android:gravity="center_horizontal|bottom" android:text="Pink" android:textColor="@color/pink_accent" android:textStyle="bold" android:theme="@style/ThemeRadioButton.Pink" /> <android.support.v7.widget.AppCompatRadioButton android:id="@+id/radio_btn_theme_grey" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="@integer/int_1" android:button="@null" android:drawableTop="?android:attr/listChoiceIndicatorSingle" android:gravity="center_horizontal|bottom" android:text="Grey" android:textColor="@color/persian_grey_dark" android:textStyle="bold" android:theme="@style/ThemeRadioButton.Grey" /> <android.support.v7.widget.AppCompatRadioButton android:id="@+id/radio_btn_theme_green" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="@integer/int_1" android:button="@null" android:drawableTop="?android:attr/listChoiceIndicatorSingle" android:gravity="center_horizontal|bottom" android:text="Green" android:textColor="@color/persian_green_accent" android:textStyle="bold" android:theme="@style/ThemeRadioButton.Green" /> <android.support.v7.widget.AppCompatRadioButton android:id="@+id/radio_btn_theme_purple" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="@integer/int_1" android:button="@null" android:drawableTop="?android:attr/listChoiceIndicatorSingle" android:gravity="center_horizontal|bottom" android:text="Purple" android:textColor="@color/purple_accent" android:textStyle="bold" android:theme="@style/ThemeRadioButton.Purple" /> </RadioGroup> </LinearLayout> </android.support.v7.widget.CardView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/dimen_25dp" android:gravity="center" android:orientation="horizontal" android:paddingRight="@dimen/dimen_10dp"> <Button android:id="@+id/pay_now_button" style="@style/ButtonStyle" android:layout_marginLeft="@dimen/dimen_10dp" android:layout_weight="1" android:text="Pay Now" /> </LinearLayout> <TextView android:id="@+id/logout_button" style="@style/ButtonStyle" android:layout_margin="@dimen/dimen_10dp" android:onClick="onClick" android:text="@string/log_out_user" /> </LinearLayout> </ScrollView> </LinearLayout>Set Styles :<resources> <!-- <!– Base application theme. –> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!– Customize your theme here. –> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style>--> <style name="AppTheme" parent="AppTheme.Base"> <item name="android:windowBackground">@android:color/white</item> <item name="windowActionBar">false</item> <item name="windowActionModeOverlay">true</item> </style> <style name="AppTheme.Base" parent="PayumoneyAppTheme"> <item name="colorPrimary">@color/primary</item> <item name="colorPrimaryDark">@color/primary_dark</item> <item name="colorAccent">@color/accent</item> <item name="colorButtonNormal">@color/primary</item> </style> <style name="AppTheme.Green" parent="PayumoneyAppTheme"> <item name="colorPrimary">@color/persian_green_primary</item> <item name="colorPrimaryDark">@color/persian_green_dark</item> <item name="colorAccent">@color/persian_green_accent</item> <item name="colorButtonNormal">@color/persian_green_primary</item> <item name="alertDialogTheme">@style/AlertDialogStyle_green</item> <item name="actionMenuTextColor">@color/white</item> </style> <style name="ThemeRadioButton.Green"> <item name="colorControlNormal">@color/persian_green_accent</item> <item name="colorControlActivated">@color/persian_green_accent</item> </style> <style name="AlertDialogStyle_green" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="colorAccent">@color/persian_green_accent</item> <item name="android:textColorPrimary">@color/payumoney_text_color</item> </style> <style name="AppTheme.pink" parent="PayumoneyAppTheme"> <item name="colorPrimary">@color/pink_primary</item> <item name="colorPrimaryDark">@color/pink_dark</item> <item name="colorAccent">@color/pink_accent</item> <item name="colorButtonNormal">@color/pink_primary</item> <item name="alertDialogTheme">@style/AlertDialogStyle_pink</item> <item name="actionMenuTextColor">@color/white</item> </style> <style name="ThemeRadioButton" parent="Theme.AppCompat.Light" /> <style name="AppTheme.default" parent="PayumoneyAppTheme"> <item name="colorPrimary">@color/orange_accent</item> <item name="colorPrimaryDark">@color/orange_accent</item> <item name="colorAccent">@color/orange_accent</item> <item name="colorButtonNormal">@color/orange_accent</item> <item name="alertDialogTheme">@style/AlertDialogStyle_Default</item> <item name="actionMenuTextColor">@color/white</item> </style> <style name="ThemeRadioButton.Default"> <item name="colorControlNormal">@color/orange_accent</item> <item name="colorControlActivated">@color/orange_accent</item> </style> <style name="AlertDialogStyle_Default" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="colorAccent">@color/orange_accent</item> <item name="android:textColorPrimary">@color/payumoney_text_color</item> </style> <style name="ThemeRadioButton.Pink"> <item name="colorControlNormal">@color/pink_accent</item> <item name="colorControlActivated">@color/pink_accent</item> </style> <style name="AlertDialogStyle_pink" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="colorAccent">@color/pink_accent</item> <item name="android:textColorPrimary">@color/payumoney_text_color</item> </style> <style name="AppTheme.blue" parent="PayumoneyAppTheme"> <item name="colorPrimary">@color/royal_blue_primary</item> <item name="colorPrimaryDark">@color/royal_blue_dark</item> <item name="colorAccent">@color/royal_blue_accent</item> <item name="colorButtonNormal">@color/royal_blue_primary</item> <item name="alertDialogTheme">@style/AlertDialogStyle_blue</item> <item name="actionMenuTextColor">@color/white</item> </style> <style name="ThemeRadioButton.Blue"> <item name="colorControlNormal">@color/royal_blue_accent</item> <item name="colorControlActivated">@color/royal_blue_accent</item> </style> <style name="AlertDialogStyle_blue" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="colorAccent">@color/royal_blue_accent</item> <item name="android:textColorPrimary">@color/payumoney_text_color</item> </style> <style name="AppTheme.purple" parent="PayumoneyAppTheme"> <item name="colorPrimary">@color/purple_primary</item> <item name="colorPrimaryDark">@color/purple_dark</item> <item name="colorAccent">@color/purple_accent</item> <item name="colorButtonNormal">@color/purple_primary</item> <item name="alertDialogTheme">@style/AlertDialogStyle_purple</item> <item name="actionMenuTextColor">@color/white</item> </style> <style name="ThemeRadioButton.Purple"> <item name="colorControlNormal">@color/purple_accent</item> <item name="colorControlActivated">@color/purple_accent</item> </style> <style name="AlertDialogStyle_purple" parent="PayumoneyAppTheme"> <item name="colorAccent">@color/purple_accent</item> <item name="android:textColorPrimary">@color/payumoney_text_color</item> </style> <style name="ButtonStyle"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:paddingBottom">@dimen/dimen_10dp</item> <item name="android:paddingTop">@dimen/dimen_10dp</item> <item name="android:textColor">@color/white</item> <item name="android:textSize">@dimen/dimen_18sp</item> <item name="android:background">@drawable/bg_rounded_button</item> <item name="android:gravity">center</item> </style> <style name="MySwitch" parent="Theme.AppCompat.Light"> <!-- active thumb & track color (30% transparency) --> <item name="colorControlActivated">@color/indigo</item> <!-- inactive thumb color --> <item name="colorSwitchThumbNormal">@color/pink</item> <!-- inactive track color (30% transparency) --> <item name="android:colorForeground">@color/grey</item> </style> <style name="AppTheme.Grey" parent="PayumoneyAppTheme"> <item name="colorPrimary">@color/persian_grey_primary</item> <item name="colorPrimaryDark">@color/persian_grey_dark</item> <item name="colorAccent">@color/persian_grey_accent</item> <item name="colorButtonNormal">@color/persian_grey_primary</item> <item name="alertDialogTheme">@style/AlertDialogStyle_grey</item> <item name="actionMenuTextColor">@color/white</item> </style> <style name="ThemeRadioButton.Grey"> <item name="colorControlNormal">@color/persian_grey_accent</item> <item name="colorControlActivated">@color/persian_grey_accent</item> </style> <style name="AlertDialogStyle_grey" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="colorAccent">@color/persian_grey_accent</item> <item name="android:textColorPrimary">@color/payumoney_text_color</item> </style> <color name="persian_grey_primary">#616161</color> <color name="persian_grey_dark">#424242</color> <color name="persian_grey_accent">#9e9e9e</color> </resources>SET COLOR CODE:<?xml version="1.0" encoding="utf-8"?><resources> <color name="primary">#7AA4D5</color> <color name="primary_dark">#165E8B</color> <color name="accent">#7AA4D5</color> <color name="white">#FFFFFF</color> <color name="persian_green_primary">#0DAC8F</color> <color name="persian_green_dark">#0A927A</color> <color name="persian_green_accent">#0A927A</color> <color name="pink_primary">#EB1E63</color> <color name="pink_dark">#C0175C</color> <color name="pink_accent">#C0175C</color> <color name="royal_blue_primary">#4C63E2</color> <color name="royal_blue_dark">#4055BF</color> <color name="royal_blue_accent">#4055BF</color> <color name="purple_primary">#9C28B1</color> <color name="purple_dark">#7A1FA2</color> <color name="purple_accent">#7A1FA2</color> <color name="orange_accent">#F3A62E</color> <color name="indigo">#3E50AE</color> <color name="pink">#FF427C</color> <color name="grey">#C2C2C2</color> </resources>
Post a Comment
0Comments