Skip to content

Instantly share code, notes, and snippets.

@TheAlphamerc
Created March 7, 2019 04:26
Show Gist options
  • Save TheAlphamerc/be6885e8f15bfe81df1fa88302a3415b to your computer and use it in GitHub Desktop.
Save TheAlphamerc/be6885e8f15bfe81df1fa88302a3415b to your computer and use it in GitHub Desktop.
Stripe payment gateway In xamarin forms
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Nonco.Model.PaymentGatway
{
public class CreditCardModel
{
[JsonProperty("exp_month")]
public long? ExpMonth { get; set; }
[JsonProperty("exp_year")]
public long? ExpYear { get; set; }
[JsonProperty("number")]
public string Number { get; set; }
[JsonProperty("address_city")]
public string AddressCity { get; set; }
[JsonProperty("address_country")]
public string AddressCountry { get; set; }
[JsonProperty("address_line1")]
public string AddressLine1 { get; set; }
[JsonProperty("address_line2")]
public string AddressLine2 { get; set; }
[JsonProperty("address_state")]
public string AddressState { get; set; }
[JsonProperty("address_zip")]
public string AddressZip { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("cvc")]
public string Cvc { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("metadata")]
public object MetaData { get; set; }
[JsonProperty("issuing_card")]
public string IssuingCardId { get; set; }
}
}
using Acr.UserDialogs;
using Nonco.Model.PaymentGatway;
using Nonco.Views.InfoPage;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Stripe;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Nonco.ViewModels
{
public class PaymentGatwayPageViewModel : BindableBase
{
#region Variable
private CreditCardModel _creditCardModel;
private TokenService Tokenservice;
private Token stripeToken;
private bool _isCarcValid;
private bool _isTransectionSuccess;
private string _expMonth;
private string _expYear;
private string _title;
#endregion Variable
#region Public Property
private string StripeTestApiKey = "{Your Stripe Api Key}";
public string ExpMonth
{
get { return _expMonth; }
set { SetProperty(ref _expMonth, value); }
}
public bool IsCarcValid
{
get { return _isCarcValid; }
set { SetProperty(ref _isCarcValid, value); }
}
public bool IsTransectionSuccess
{
get { return _isTransectionSuccess; }
set { SetProperty(ref _isTransectionSuccess, value); }
}
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public string ExpYear
{
get { return _expYear; }
set { SetProperty(ref _expYear, value); }
}
public CreditCardModel CreditCardModel
{
get { return _creditCardModel; }
set { SetProperty(ref _creditCardModel, value); }
}
#endregion Public Property
#region Constructor
public PaymentGatwayPageViewModel()
{
CreditCardModel = new CreditCardModel();
Title = "Card Details";
}
#endregion Constructor
#region Command
public DelegateCommand SubmitCommand => new DelegateCommand(async () =>
{
CreditCardModel.ExpMonth = Convert.ToInt64(ExpMonth);
CreditCardModel.ExpYear = Convert.ToInt64(ExpYear);
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
try
{
UserDialogs.Instance.ShowLoading("Payment processing..");
await Task.Run(async () =>
{
var Token = CreateToken();
Console.Write("Payment Gateway" + "Token :" + Token);
if (Token != null)
{
IsTransectionSuccess = MakePayment(Token);
}
else
{
UserDialogs.Instance.Alert("Bad card credentials", null, "OK");
}
});
}
catch (Exception ex)
{
UserDialogs.Instance.HideLoading();
UserDialogs.Instance.Alert(ex.Message, null, "OK");
Console.Write("Payment Gatway" + ex.Message);
}
finally
{
if (IsTransectionSuccess)
{
Console.Write("Payment Gateway" + "Payment Successful ");
UserDialogs.Instance.HideLoading();
}
else
{
UserDialogs.Instance.HideLoading();
UserDialogs.Instance.Alert("Oops, something went wrong","Payment failed","OK");
Console.Write("Payment Gateway" + "Payment Failure ");
}
}
});
#endregion Command
#region Method
private string CreateToken()
{
try
{
StripeConfiguration.SetApiKey(StripeTestApiKey);
var service = new ChargeService();
var Tokenoptions = new TokenCreateOptions
{
Card = new CreditCardOptions
{
Number = CreditCardModel.Number,
ExpYear = CreditCardModel.ExpYear,
ExpMonth = CreditCardModel.ExpMonth,
Cvc = CreditCardModel.Cvc,
Name = "Sonu Sharma",
AddressLine1 = "18",
AddressLine2 = "SpringBoard",
AddressCity = "Gurgoan",
AddressZip = "284005",
AddressState = "Haryana",
AddressCountry = "India",
Currency = "inr",
}
};
Tokenservice = new TokenService();
stripeToken = Tokenservice.Create(Tokenoptions);
return stripeToken.Id;
}
catch (Exception ex)
{
throw ex;
}
}
public bool MakePayment(string token)
{
try
{
StripeConfiguration.SetApiKey(StripeSecreatApiKey);
var options = new ChargeCreateOptions
{
Amount = (long)float.Parse("20000"),
Currency = "inr",
Description = "Charge for Jon.rosen@example.com",
SourceId = stripeToken.Id,
StatementDescriptor = "Custom descriptor",
Capture = true,
ReceiptEmail = "sonu.sharma@gmail.com",
};
//Make Payment
var service = new ChargeService();
Charge charge = service.Create(options);
return true;
}
catch (Exception ex)
{
Console.Write("Payment Gatway (CreateCharge)"+ ex.Message);
throw ex;
}
}
private bool ValidateCard()
{
if (CreditCardModel.Number.Length == 16 && ExpMonth.Length == 2 && ExpYear.Length == 2 && CreditCardModel.Cvc.Length == 3)
{
}
return true;
}
#endregion Method
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="Nonco.Views.InfoPage.PaymentGatwayPage">
<NavigationPage.TitleView>
<Grid HorizontalOptions="FillAndExpand">
<Image Source="HeaderLogo" Aspect="AspectFit" HorizontalOptions="Center" VerticalOptions="Center" Margin="-60,0,0,0"/>
</Grid>
</NavigationPage.TitleView>
<ContentView>
<StackLayout VerticalOptions="FillAndExpand">
<Grid HorizontalOptions="Center" Padding="20,20,20,0" ColumnSpacing="20">
<Grid.RowDefinitions >
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<StackLayout Grid.Row="0" Grid.ColumnSpan="2">
<Entry x:Name="CardNumber" Placeholder=" Enter card number" Text="{Binding CreditCardModel.Number}" ReturnType="Next"
Completed="CardNumber_Completed" TextChanged="CardNumber_TextChanged" Keyboard="Keyboard.Numeric"/>
<Label x:Name="ErrorLabel_CardNumber" IsVisible="{Binding IsError_CardNumber}" TextColor="Red" FontSize="13" />
</StackLayout>
<StackLayout Grid.Row="1" Grid.Column="0">
<Entry x:Name="Month" Placeholder=" MM" Text="{Binding ExpMonth}" ReturnType="Next" Keyboard="Keyboard.Numeric"
Completed="Month_Completed" TextChanged="Month_TextChanged"/>
<Label x:Name="ErrorLabel_Month" IsVisible="{Binding IsError_Month}" TextColor="Red" FontSize="13"/>
</StackLayout>
<StackLayout Grid.Row="1" Grid.Column="1">
<Entry x:Name="Year" Placeholder=" YY" Text="{Binding ExpYear}" ReturnType="Next"
Completed="Year_Completed" TextChanged="Year_TextChanged" Keyboard="Keyboard.Numeric"/>
<Label x:Name="ErrorLabel_Year" Text="year can be empty !!" IsVisible="{Binding IsError_Year}" TextColor="Red" FontSize="13"/>
</StackLayout>
<StackLayout Grid.Row="2" Grid.ColumnSpan="2">
<Entry x:Name="Cvv" Placeholder=" Cvv code" Text="{Binding CreditCardModel.Cvc}" ReturnType="Next"
Completed="Cvv_Completed" TextChanged="Cvv_TextChanged" Keyboard="Keyboard.Numeric"/>
<Label x:Name="ErrorLabel_Cvv" Text="CVV can not be empty !!" IsVisible="{Binding IsError_Cvv}" TextColor="Red" FontSize="13" />
</StackLayout>
</Grid>
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="End" >
<Button x:Name="Submit_Button" BorderRadius="0" Text="Submit" Command="{Binding SubmitCommand}" HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand"/>
</StackLayout>
</StackLayout>
</ContentView>
</ContentPage>
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Nonco.Views.InfoPage
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PaymentGatwayPage : ContentPage
{
public PaymentGatwayPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
Submit_Button.IsEnabled = false;
ErrorLabel_CardNumber.IsVisible = false;
ErrorLabel_Cvv.IsVisible = false;
ErrorLabel_Month.IsVisible = false;
ErrorLabel_Year.IsVisible = false;
}
private void CardNumber_TextChanged(object sender, TextChangedEventArgs e)
{
if (CardNumber.Text.Length > 16)
{
ErrorLabel_CardNumber.IsVisible = true;
CardNumber.Text = RemoveLastCharacter(CardNumber.Text);
ErrorLabel_CardNumber.Text = "Invalid Card number";
}
else if (CardNumber.Text.Length < 1)
{
ErrorLabel_CardNumber.IsVisible = true;
ErrorLabel_CardNumber.Text = "Card number can not be empty !!";
}
else
{
ErrorLabel_CardNumber.IsVisible = false;
}
EnableSubmitButton();
}
private void CardNumber_Completed(object sender, System.EventArgs e)
{
if (CardNumber.Text.Length > 16 || CardNumber.Text.Length < 12)
{
ErrorLabel_CardNumber.IsVisible = true;
ErrorLabel_CardNumber.Text = "Invalid Card number";
EnableSubmitButton();
}
else
{
ErrorLabel_CardNumber.IsVisible = false;
}
CardNumber.Unfocus();
Month.Focus();
EnableSubmitButton();
}
private void Month_TextChanged(object sender, TextChangedEventArgs e)
{
if (Month.Text.Length < 1)
{
ErrorLabel_Month.IsVisible = true;
ErrorLabel_Month.Text = "month can not be empty !!";
}
else if (Month.Text.Length > 2)
{
Month.Text = RemoveLastCharacter(Month.Text);
ErrorLabel_Month.IsVisible = true;
ErrorLabel_Month.Text = "Invalid month !!";
}
else
{
ErrorLabel_Month.IsVisible = false;
EnableSubmitButton();
}
EnableSubmitButton();
}
private void Month_Completed(object sender, System.EventArgs e)
{
Month.Unfocus();
Year.Focus();
}
private void Year_TextChanged(object sender, TextChangedEventArgs e)
{
if (Year.Text.Length < 1)
{
ErrorLabel_Year.IsVisible = true;
ErrorLabel_Year.Text = "month can not be empty !!";
}
else if (Year.Text.Length > 2)
{
Year.Text = RemoveLastCharacter(Year.Text);
ErrorLabel_Year.IsVisible = true;
ErrorLabel_Year.Text = "Invalid year !!";
}
else
{
ErrorLabel_Year.IsVisible = false;
EnableSubmitButton();
}
EnableSubmitButton();
}
private void Year_Completed(object sender, System.EventArgs e)
{
Year.Unfocus();
Cvv.Focus();
}
private void Cvv_TextChanged(object sender, TextChangedEventArgs e)
{
if (Cvv.Text.Length < 1)
{
ErrorLabel_Cvv.IsVisible = true;
ErrorLabel_Cvv.Text = "CVV can not be empty !!";
}
else if (Cvv.Text.Length > 3)
{
Cvv.Text = RemoveLastCharacter(Cvv.Text);
ErrorLabel_Cvv.IsVisible = true;
ErrorLabel_Cvv.Text = "Invalid Cvv !!";
}
else
{
ErrorLabel_Cvv.IsVisible = false;
EnableSubmitButton();
}
EnableSubmitButton();
}
private void Cvv_Completed(object sender, System.EventArgs e)
{
Cvv.Unfocus();
}
private void EnableSubmitButton()
{
if (ErrorLabel_CardNumber.IsVisible || ErrorLabel_Cvv.IsVisible || ErrorLabel_Month.IsVisible || ErrorLabel_Year.IsVisible)
{
Submit_Button.IsEnabled = false;
}
else
{
Submit_Button.IsEnabled = true;
}
}
private string RemoveLastCharacter(string str)
{
int l = str.Length;
string text = str.Remove(l-1,1);
return text;
}
}
}
@lntserviceiq5
Copy link

Hi Sonu,

Can you please share the entire project.. So i can integrate to my Xamarin Forms project.

@TheAlphamerc
Copy link
Author

Hi @lntserviceiq5, you can easily use these files in your project by following below steps :

  1. Create new project.

  2. Install Stripe nuget.

  3. Add a new page StripePaymentGatwayPage , a model and a view Model.

  4. Copy code from above files and paste into your files.

  5. If you use whole code from StripePaymentGatwayPageViewModel file then you have to install nuget packages used in this file like Acr.UserDialogs etc.

  6. For using stripe gatway you have to create account in Stripe website and get a key from there.

  7. For further information please visit :- Stripe.com

@lntserviceiq5
Copy link

Hi Sonu,

Did Stripe Support for UPI(Unified Payments Interface) payments and digital wallets as well?

@TheAlphamerc
Copy link
Author

No Stripe only support Card payment method

@JArmandoCl
Copy link

JArmandoCl commented Jul 3, 2020

Hi TheAlphamerc! Thanks for de code, i have a question, where do you use the token? because en this part of code the var token is not used
public bool MakePayment(string token) { try { StripeConfiguration.SetApiKey(StripeSecreatApiKey); var options = new ChargeCreateOptions { Amount = (long)float.Parse("20000"), Currency = "inr", Description = "Charge for Jon.rosen@example.com", Source = stripeToken.Id, StatementDescriptor = "Custom descriptor", Capture = true, ReceiptEmail = "sonu.sharma@gmail.com", }; //Make Payment var service = new ChargeService(); Charge charge = service.Create(options); return true; } catch (Exception ex) { Console.Write("Payment Gatway (CreateCharge)" + ex.Message); throw ex; } }

Thanks!

@KevinAnass
Copy link

ipe only supp

thank you for this repo sir
one question if you can
how I can pass the amount of payment?

@DavidLee1216
Copy link

Hi, TheAlphamerc,
Can I use this code on Xamarin Android project?
I tried it to use, but when call tokenService.Create(tokenoption), it gives me error that says "System.ArgumentException: Get Method not found for 'Card' at System.Reflection.RuntimePropertyInfo.GetValue ........".

@TheAlphamerc
Copy link
Author

Hi, TheAlphamerc, Can I use this code on Xamarin Android project? I tried it to use, but when call tokenService.Create(tokenoption), it gives me error that says "System.ArgumentException: Get Method not found for 'Card' at System.Reflection.RuntimePropertyInfo.GetValue ........".

This code doesn't support Xamarin android. It will only works with xamarin form.

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