Skip to content

Instantly share code, notes, and snippets.

@TheAlphamerc
Last active July 10, 2024 19:02
Show Gist options
  • Save TheAlphamerc/f54228336fcadd3913a1dced1ca95a81 to your computer and use it in GitHub Desktop.
Save TheAlphamerc/f54228336fcadd3913a1dced1ca95a81 to your computer and use it in GitHub Desktop.
Phonepay and Bhim app payment in xamarin form
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using SampleApp.Droid.PaymentActivity;
using SampleApp.Droid.Service;
using SampleApp.Interface.PaymentInterface;
using Plugin.CurrentActivity;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(AppPaymentService))]
namespace SampleApp.Droid.Service
{
public class AppPaymentService : IAppPaymentService
{
public string BhimPay(string amount)
{
Intent intent = new Intent(nameof(BhimPayActivity));
intent = new Intent(CrossCurrentActivity.Current.Activity, typeof(BhimPayActivity));
intent.PutExtra("amount", amount);
intent.AddFlags(ActivityFlags.ClearTop);
CrossCurrentActivity.Current.Activity.StartActivity(intent);
return "";
}
public string GooglePay(string amount)
{
Intent intent = new Intent(nameof(GooglePayActivity));
intent = new Intent(CrossCurrentActivity.Current.Activity, typeof(GooglePayActivity));
intent.PutExtra("amount", amount);
intent.AddFlags(ActivityFlags.ClearTop);
CrossCurrentActivity.Current.Activity.StartActivity(intent);
return "";
}
public string IciciPay(string amount)
{
return "";
}
public string PayTm(string amount)
{
Intent intent = new Intent(nameof(PayTmActivity));
intent = new Intent(CrossCurrentActivity.Current.Activity, typeof(PayTmActivity));
intent.PutExtra("amount", amount);
intent.AddFlags(ActivityFlags.ClearTop);
CrossCurrentActivity.Current.Activity.StartActivity(intent);
return "";
}
public string PhonePay(string amount)
{
Intent intent = new Intent(nameof(PhonePeActivity));
intent = new Intent(CrossCurrentActivity.Current.Activity, typeof(PhonePeActivity));
intent.PutExtra("amount", amount);
intent.AddFlags(ActivityFlags.ClearTop);
CrossCurrentActivity.Current.Activity.StartActivity(intent);
return "";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
namespace SampleApp.Droid.PaymentActivity
{
[Activity(Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class BhimPayActivity : Activity
{
string status = "";
string TrnxacsnId = "";
List<string> ResponseList = new List<string>();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
try
{
string amount = Intent.GetStringExtra("amount");
long tsLong = JavaSystem.CurrentTimeMillis() / 1000;
string transaction_ref_id = Guid.NewGuid().ToString().Substring(0,10) + "UPI";
string transaction_ref = Guid.NewGuid().ToString().Substring(0, 10);
Log.Write("TR Reference ID==>", "" + transaction_ref_id);
using (var uri = new Android.Net.Uri.Builder()
.Scheme("upi")
.Authority("pay")
.AppendQueryParameter("pa", Constants.PaymentUpiId)
// .AppendQueryParameter("pa", "7017958029@upi")
.AppendQueryParameter("pn", "Nonco")
.AppendQueryParameter("mc", "0000")
.AppendQueryParameter("tid", transaction_ref)
.AppendQueryParameter("tr", transaction_ref_id)
.AppendQueryParameter("tn", "Pay to nonco")
.AppendQueryParameter("am", amount)
.AppendQueryParameter("cu", "INR")
.AppendQueryParameter("url", "https://www.sample.in")
.Build())
{
Intent = new Intent(Intent.ActionView);
Intent.SetData(uri);
if (IsAppInstalled("in.org.npci.upiapp"))
{
Intent.SetPackage("in.org.npci.upiapp");
StartActivityForResult(Intent, 9999);
}
else
{
var package = PackageName;
Toast.MakeText(Android.App.Application.Context, "Bhim is not available in this device", ToastLength.Long).Show();
this.Finish();
}
}
}
catch (System.Exception ex)
{
Toast.MakeText(Android.App.Application.Context, "Payment through Bhim is failed", ToastLength.Long).Show();
this.Finish();
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == 9999)
{
Console.WriteLine("Bhim pay result", data);
if (resultCode == Result.Ok)
{
GetResponseFromIntent(data?.Extras);
}
else if (resultCode == Result.Canceled)
{
Toast.MakeText(Android.App.Application.Context, "Payment through Bhim failed", ToastLength.Long).Show();
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("Exception while Bhim payment :" + ex.Message);
ShowToast("Payment through Bhim failed"); //! Failed
}
if(status == "success")
{
var tranData = new Tuple<bool, string>(true, TrnxacsnId);
Console.Write("Phonepe Messenging center [] status : success");
MessagingCenter.Send("PayStatus", "PayStatus", tranData);
}
else
{
var tranData = new Tuple<bool, string>(false, null);
Console.Write("Phonepe Messenging center [] status : failed");
MessagingCenter.Send("PayStatus", "PayStatus", tranData);
}
Finish();
}
private void GetResponseFromIntent(Bundle extras)
{
Dictionary<string, string> dict;
dict = new Dictionary<string, string>();
if (extras != null)
{
foreach (var key in extras.KeySet())
{
dict.Add(key, extras.Get(key).ToString());
ResponseList.Add(key + ":"+ extras.Get(key).ToString());
if (key == "Status" && extras.Get(key).ToString().Contains("FAILURE"))
{
Toast.MakeText(Android.App.Application.Context, "Payment through Bhim fail", ToastLength.Long).Show();
status = "failed";
}
if (key == "Status" && extras.Get(key).ToString().Contains("SUCCESS"))
{
Toast.MakeText(Android.App.Application.Context, "Payment through Bhim success", ToastLength.Long).Show();
status = "success";
}
if (key == "responseCode")
{
Console.WriteLine("Response code [] " + extras.Get(key).ToString());
}
if(key == "txnid")
{
TrnxacsnId = extras.Get(key).ToString();
}
}
}
}
private bool IsAppInstalled(string packageName)
{
PackageManager pm = this.PackageManager;
bool installed = false;
try
{
pm.GetPackageInfo(packageName, PackageInfoFlags.Activities);
installed = true;
}
catch (PackageManager.NameNotFoundException e)
{
installed = false;
}
return installed;
}
private void ShowToast(string message)
{
Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long).Show();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Interop;
using Java.Lang;
namespace SampleApp.Droid.PaymentActivity
{
[Activity(Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class GooglePayActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
try
{
long tsLong = JavaSystem.CurrentTimeMillis() / 1000;
string transaction_ref_id = tsLong.ToString() + "UPI";
using (var uri = new Android.Net.Uri.Builder()
.Scheme("upi")
.Authority("pay")
.AppendQueryParameter("pa", "7017958029@upi")
.AppendQueryParameter("pn", "Sonu Sharma")
.AppendQueryParameter("mc", null)
.AppendQueryParameter("tid", null)
.AppendQueryParameter("tr", transaction_ref_id)
.AppendQueryParameter("tn", "Test integration note")
.AppendQueryParameter("am", "1.00")
.AppendQueryParameter("cu", "INR")
.Build())
{
Intent = new Intent(Intent.ActionView);
Intent.SetData(uri);
if (IsAppInstalled("com.google.android.apps.nbu.paisa.user"))
{
Intent.SetPackage("com.google.android.apps.nbu.paisa.user");
StartActivityForResult(Intent, 9999);
}
else
{
var package = PackageName;
ShowToast("Google pay is not available in this device");
this.Finish();
}
}
}
catch (System.Exception ex)
{
ShowToast("Payment through Google Pay failed");
this.Finish();
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
try
{
if (requestCode == 9999)
{
Android.Util.Log.Debug("Google pay result", data.GetStringExtra("Status"));
if (data.GetStringExtra("Status").Contains("SUCCESS"))
{
ShowToast("Payment through Google Pay success"); //! Success
// SetSetting("SUCCESS");
}
else
{
ShowToast("Payment through Google Pay failed"); //! Fail
// SetSetting("FAILURE");
}
}
var b = data?.Extras;
var d = new Dictionary<string, string>();
if (b != null)
{
foreach (var key in b.KeySet())
{
d.Add(key, b.Get(key).ToString());
if (key == "Status" && b.Get(key).ToString().Contains("FAILURE"))
{
ShowToast("Payment through Google pay fail"); //! If failed
}
if (key == "Status" && b.Get(key).ToString().Contains("SUCCESS"))
{
ShowToast("Payment through Google pay success"); //! If success
}
}
}
}
catch (System.Exception ex)
{
Console.WriteLine("Exception while google payment :" + ex.Message);
ShowToast("Payment through Google pay failed"); //! If any exception occur
}
this.Finish();
}
private bool IsAppInstalled(string packageName)
{
PackageManager pm = this.PackageManager;
bool installed = false;
try
{
pm.GetPackageInfo(packageName, PackageInfoFlags.Activities);
installed = true;
}
catch (PackageManager.NameNotFoundException e)
{
installed = false;
}
return installed;
}
private void ShowToast(string message)
{
Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long).Show();
}
public override void OnBackPressed()
{
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace SampleApp.Interface.PaymentInterface
{
public interface IAppPaymentService
{
string GooglePay(string amount);
string PhonePay(string amount);
string IciciPay(string amount);
string BhimPay(string amount);
string PayTm(string amount);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Xamarin.Forms;
namespace SampleApp.Droid.PaymentActivity
{
[Activity(Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class PhonePeActivity : Activity
{
string status = "";
List<string> ResponseList = new List<string>();
public string TrnxacsnId { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
try
{
string amount = Intent.GetStringExtra("amount");
long tsLong = JavaSystem.CurrentTimeMillis() / 1000;
string transaction_ref_id = tsLong.ToString() + "UPI";
using (var uri = new Android.Net.Uri.Builder()
.Scheme("upi")
.Authority("pay")
.AppendQueryParameter("pa", Constants.PaymentUpiId)
// .AppendQueryParameter("pa", "7017958029@upi")
.AppendQueryParameter("pn", "Sonu Sharma")
.AppendQueryParameter("tn", "Test integration note")
.AppendQueryParameter("tr", transaction_ref_id)
.AppendQueryParameter("am", amount)
.AppendQueryParameter("cu", "INR")
.Build())
{
Intent = new Intent(Intent.ActionView);
Intent.SetData(uri);
if (IsAppInstalled("com.phonepe.app"))
{
Intent.SetPackage("com.phonepe.app");
StartActivityForResult(Intent, 9999);
}
else
{
var package = PackageName;
Toast.MakeText(Android.App.Application.Context, "Phonepe is not available in this device", ToastLength.Long).Show();
this.Finish();
}
}
}
catch (System.Exception ex)
{
Toast.MakeText(Android.App.Application.Context, "Payment through PhonePe failed", ToastLength.Long).Show();
Console.WriteLine("Error", ex.Message);
this.Finish();
}
}
private bool IsAppInstalled(string packageName)
{
PackageManager pm = this.PackageManager;
bool installed = false;
try
{
pm.GetPackageInfo(packageName, PackageInfoFlags.Activities);
installed = true;
}
catch (PackageManager.NameNotFoundException e)
{
installed = false;
}
return installed;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Canceled)
{
Toast.MakeText(Android.App.Application.Context, "Payment through PhonePe Failed", ToastLength.Long).Show();
}
else if(resultCode == Result.Ok)
{
var b = data?.Extras;
var d = new Dictionary<string, string>();
if (b != null)
{
foreach (var key in b.KeySet())
{
d.Add(key, b.Get(key).ToString());
ResponseList.Add(key + ":" + b.Get(key).ToString());
if (key == "Status" && b.Get(key).ToString().Contains("Failure"))
{
Toast.MakeText(Android.App.Application.Context, "Payment through Phonepe fail", ToastLength.Long).Show();
status = "Failed";
}
if (key == "Status" && b.Get(key).ToString().Contains("Success"))
{
Toast.MakeText(Android.App.Application.Context, "Payment through Phonepe success", ToastLength.Long).Show();
status = "Success";
}
if (key == "bleTxId")
{
Console.WriteLine("Phonepe[] transection id :" + b.Get(key).ToString());
}
if (key == "txnid")
{
TrnxacsnId = b.Get(key).ToString();
}
}
}
} Finish();
}
}
}
@hozrotali
Copy link

Paytm activity/implementation is not available, please add.

@ashishjangir
Copy link

Please Add Paytm Activity

@TheAlphamerc
Copy link
Author

Update intent call section by below code in PhonePeActivity. It will be started to work for Paytm.

                {
                    Intent = new Intent(Intent.ActionView);
                    Intent.SetData(uri);
                    if (IsAppInstalled("net.one97.paytm"))
                    {
                        Intent.SetPackage("net.one97.paytm");
                        StartActivityForResult(Intent, 9999);
                    }
               }

@ErBhautik
Copy link

ErBhautik commented Jul 27, 2021

I have clone the source code and change the QueryParameter pa to my Gpay UPI and run the code in my android mobile. but after the Pin verification is says "You've exceeded the maximum transaction amount set by your bank". and the translation failed. If I'm doing the normal payment it is working fine.

@TheAlphamerc
Copy link
Author

@ErBhautik this is related to your transaction quota, maybe quota for specific to the merchant or your UPI.

@ashishjangir
Copy link

ashishjangir commented Jul 28, 2021 via email

@ErBhautik
Copy link

@ErBhautik this is related to your transaction quota, maybe quota for specific to the merchant or your UPI.

This is happening for other upi as well.This is something related to privacy.

For phone pay I'm getting error that you are not allowed to send money from your bank For this transaction.

For paytm I'm getting error that payment mode is not allowed for this UPI ID.

For BhIM upi I got the error RISK THRESOLD EXCEEDED.

@ErBhautik
Copy link

please enable google business upi.. take business upi from google pay business app and put this upi in your upi intent may be its help for you . because now i am accepting payment from upi intent using gpay bussing upi.

On Wed, 28 Jul, 2021, 9:46 am Sonu Sharma, @.> wrote: @.* commented on this gist. ------------------------------ @ErBhautik https://github.com/ErBhautik this is related to your transaction quota, maybe quota for specific to the merchant or your UPI. — You are receiving this because you commented. Reply to this email directly, view it on GitHub https://gist.github.com/f54228336fcadd3913a1dced1ca95a81#gistcomment-3831988, or unsubscribe https://github.com/notifications/unsubscribe-auth/AEVSN4LGHELKTTJWOCPO2MTTZ6AANANCNFSM4H32VGAQ .

What about for paytm phone pay and bhim upi any idea?

@chkanth123
Copy link

Hi need some help, i am trying to implement upi payemnts using xamarin android and used all the above mentioned classed. When i try to invoke any of the UPI methods from AppPayment service, I am getting exception in following code:
public string GooglePay(string amount, string mobileNumber)
{
Intent intent = new Intent(nameof(GooglePayActivity));
intent = new Intent(CrossCurrentActivity.Current.Activity, typeof(GooglePayActivity));
intent.PutExtra("amount", amount);
intent.PutExtra("mobilenum", mobileNumber);
intent.AddFlags(ActivityFlags.ClearTop);
CrossCurrentActivity.Current.Activity.StartActivity(intent);
return "";
}
follownig link for error message. failing to create Intent i believe
IMG-20220601-WA0019

attached exceptoin details from my mobile app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment