Skip to content

Instantly share code, notes, and snippets.

@suchithm
Last active March 20, 2023 12:27
Show Gist options
  • Save suchithm/96ec16a30fb54aa07b0bef33783c8209 to your computer and use it in GitHub Desktop.
Save suchithm/96ec16a30fb54aa07b0bef33783c8209 to your computer and use it in GitHub Desktop.
Custom WebView Renderer
using System;
using Diet.iOS.CustomRenderer;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using WebKit;
using Foundation;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace CustomRenderer
{
public class CustomWebViewRenderer : WkWebViewRenderer, IWKScriptMessageHandler
{
public CustomWebViewRenderer()
{
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
LoadCustomWebview();
}
}
async private void LoadCustomWebview()
{
RazorPayload payload = new RazorPayload();
payload.amount = Constant.NetPayableAmount * 100;
payload.currency = "INR";
payload.receipt = GenerateRefNo();
payload.payment_capture = 1;
RazorResp resp;
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.razorpay.com/v1/orders"))
{
var plainTextBytes = Encoding.UTF8.GetBytes($"{Constants.RazorPay_Key}:{Constants.RazorPay_Secret}");
var basicAuthKey = Convert.ToBase64String(plainTextBytes);
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {basicAuthKey}");
string jsonData = JsonConvert.SerializeObject(payload);
request.Content = new StringContent(jsonData);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
string jsonResp = await response.Content.ReadAsStringAsync();
resp = JsonConvert.DeserializeObject<RazorResp>(jsonResp);
}
}
var js = @" <body onload=""openpaymentscreen()"">
<script src=""https://checkout.razorpay.com/v1/checkout.js""></script>
<script>
var options = {
""key"": ""@key@"",
""amount"": ""@amount@"",
""currency"": ""INR"",
""name"": ""CodeLog"",
""description"": ""AppliedCodeLog"",
""order_id"": ""@orderid@"",
""handler"": function (response){
window.webkit.messageHandlers.PaymentJSBridge.postMessage(response)
},
""modal"": {
""ondismiss"": function(){
window.webkit.messageHandlers.PaymentJSBridge.postMessage(""closed"")
}
},
""prefill"": {
""name"": ""@name@"",
""email"": ""@email@"",
""contact"": ""@contact@""
},
""config"": {
""display"": {
""hide"": [{
method: ""netbanking""
}]
}
},
""notes"": {
""address"": "" address here""
},
""theme"": {
""color"": ""#ee3a70""
}
};
var rzp1 = new Razorpay(options);
rzp1.on('payment.failed', function (response){
window.webkit.messageHandlers.PaymentJSBridge.postMessage(response);
});
function openpaymentscreen()
{
rzp1.open();
}
</script></body>";
//#33nine ninecc
js = js.Replace("@orderid@", resp.id.ToString());
js = js.Replace("@amount@", (Constant.NetPayableAmount * 100; * 100).ToString());
js = js.Replace("@key@", Constants.RazorPay_Key);
js = js.Replace("@name@", Constant.name?.ToString());
js = js.Replace("@email@", Constant.email?.ToString());
js = js.Replace("@contact@", Constant.mobileNumber?.ToString());
Configuration.Preferences.JavaScriptCanOpenWindowsAutomatically = true;
Configuration.Preferences.JavaScriptEnabled = true;
LoadHtmlString((NSString)js, null);
var _userController = Configuration.UserContentController;
_userController.AddScriptMessageHandler(this, "PaymentJSBridge");
}
}
public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
{
MessagingCenter.Send("Message", "ClosePaymentPage");//call back to close the current contentpage
var result = message?.Body;
if (result != null && result.ToString() != new NSString("closed"))
{
var paymentId = result.ValueForKey(new NSString("razorpay_payment_id"));
var orderId = result.ValueForKey(new NSString("razorpay_order_id"));
var signatureId = result.ValueForKey(new NSString("razorpay_signature"));
var error = result.ValueForKey(new NSString("error"));
if (string.IsNullOrEmpty(error?.ToString()))
{
MessagingCenter.Send<RazorPayPaymentData>("paymentId", eventKey);
}
else
{
MessagingCenter.Send<RazorPayPaymentData>("error", eventKey);
}
}
}
public static string GenerateRefNo()
{
string refNo = "";
Random ran = new Random();
String b = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int length = 6;
String random = "";
for (int i = 0; i < length; i++)
{
int a = ran.Next(26);
random = random + b.ElementAt(a);
}
int d = ran.Next(100000, 999999);
refNo = $"{random}{d}";
return refNo;
}
public class RazorPayload
{
public int amount { get; set; }
public string currency { get; set; }
public string receipt { get; set; }
public int payment_capture { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment