Pay Pal Integration in asp.net website using .net framework 4.8

pujaparekh
Contributor
Contributor

hi,

I have an asp.net (web forms) website built using .net framework 4.8 (C#) in visual studio 2019. I am not able to integrate PayPalCheckoutSdk and PayPalHttp sdk in my website.  There is a default.aspx page with pay pal button which when clicked should open pay pal login page and after user approves payment, it should return to complete.aspx page. I have 2 other pages called CreatePayPalOrder.aspx and ExecutePayPalPayment.aspx which are called when paypal's createOrder and onApprove functions are called. Now when I click on pay pal button on default page, it tries to open a pay pal login page but the pay pal pop just loads indefinitely. Please help as to what is wrong with the code. I reviewed code on github and did numerous google searches but all to a waste. Also, am not sure if the flow of code is correct. I posted a ticket to pay pal support but they are totally hopeless. 

 

Here is my code

Default.aspx

<div id="paypal-button-container"></div>

<script src="https://www.paypal.com/sdk/js?client-id=mySandboxClientId&currency=AUD"> </script><script>

paypal.Buttons({

env: 'sandbox', /* sandbox | production */
style: {
layout: 'horizontal', // horizontal | vertical
size: 'responsive', /* medium | large | responsive*/
shape: 'pill', /* pill | rect*/
color: 'gold', /* gold | blue | silver | black*/
fundingicons: false, /* true | false */
tagline: false /* true | false */
},

// Set up the transaction

createOrder: function (data) {
return fetch('/CreatePayPalOrder', {
method: 'post'
}).then(function (res) {
return res.json();
}).then(function (orderData) {
return orderData.Id; // Use the same key name for order ID on the client and server
});
},

onApprove: function (data) {
return fetch('/ExecutePayPalPayment', {
method: 'post'
}).then(function (res) {
return res.json();
}).then(function (orderData) {
alert('Transaction approved by ' + orderData.payer_given_name);
});
},

// Buyer cancelled the payment
onCancel: function (data) {
 alert(data);
},

// An error occurred during the transaction
onError: function (err) {
alert(err);
}

}).render('#paypal-button-container');</script>

 

CreatePayPalOrder.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
CreateOrder().Wait();

string OrderId = Session["PayPalOrderId"].ToString();

GetOrder(OrderId).Wait();
}

public async Task<HttpResponse> CreateOrder()
{
try
{
var request = new OrdersCreateRequest();
request.Prefer("return=representation");
request.RequestBody(BuildRequestBody());

//3. Call PayPal to set up a transaction
var response = await PayPalClient.client().Execute(request); // the code hangs on this line and never comes out

var result = response.Result<Order>();

Session["PayPalOrderId"] = result.Id;

Debug.WriteLine("Status: {0}", result.Status);
Debug.WriteLine("Order Id: {0}", result.Id);
Debug.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
Debug.WriteLine("Links:");
foreach (LinkDescription link in result.Links)
{
Debug.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
}
AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
Debug.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);

return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

private OrderRequest BuildRequestBody()
{
OrderRequest orderRequest = new OrderRequest()
{
CheckoutPaymentIntent = "CAPTURE",

ApplicationContext = new ApplicationContext
{
BrandName = "MyBrand",
LandingPage = "BILLING",
UserAction = "CONTINUE",
ReturnUrl = "https://localhost:44316/Complete",
CancelUrl = "https://localhost:44316/Default"
},
PurchaseUnits = new List<PurchaseUnitRequest>
{
new PurchaseUnitRequest{
ReferenceId = "B456",
AmountWithBreakdown = new AmountWithBreakdown
{
CurrencyCode = "AUD",
Value = "15.00"
}
}
}
};

return orderRequest;
}

public async Task<HttpResponse> GetOrder(string orderId)
{
try
{
OrdersGetRequest request = new OrdersGetRequest(orderId);
//3. Call PayPal to get the transaction
var response = await PayPalClient.client().Execute(request);
//4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
var result = response.Result<Order>();
Debug.WriteLine("Retrieved Order Status");
Debug.WriteLine("Status: {0}", result.Status);
Debug.WriteLine("Order Id: {0}", result.Id);
Debug.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
Debug.WriteLine("Links:");
foreach (LinkDescription link in result.Links)
{
Debug.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
}
AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
Debug.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);

return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

ExecutePayPalPayment.aspx.cs

 

protected void Page_Load(object sender, EventArgs e)
{
string OrderId = Session["PayPalOrderId"].ToString();

CaptureOrder(OrderId).Wait();
}

public async Task<HttpResponse> CaptureOrder(string OrderId)
{
try
{
var request = new OrdersCaptureRequest(OrderId);
request.Prefer("return=representation");
request.RequestBody(new OrderActionRequest());
//3. Call PayPal to capture an order
var response = await PayPalClient.client().Execute(request);
//4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.

var result = response.Result<Order>();
Debug.WriteLine("Status: {0}", result.Status);
Debug.WriteLine("Order Id: {0}", result.Id);
Debug.WriteLine("Intent: {0}", result.CheckoutPaymentIntent);
Debug.WriteLine("Links:");
foreach (LinkDescription link in result.Links)
{
Debug.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);
}
Debug.WriteLine("Capture Ids: ");

AmountWithBreakdown amount = result.PurchaseUnits[0].AmountWithBreakdown;
Debug.WriteLine("Buyer:");


return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

PayPalClient.cs

public class PayPalClient
{
/**
Set up PayPal environment with sandbox credentials.
In production, use LiveEnvironment.
*/
public static PayPalEnvironment environment()
{
return new SandboxEnvironment("mySandboxClientId", "mySandboxSecret");
}

/**
Returns PayPalHttpClient instance to invoke PayPal APIs.
*/
public static HttpClient client()
{
return new PayPalHttpClient(environment());
}

public static HttpClient client(string refreshToken)
{
return new PayPalHttpClient(environment(), refreshToken);
}

/**
Use this method to serialize Object to a JSON string.
*/
public static String ObjectToJSONString(Object serializableObject)
{
MemoryStream memoryStream = new MemoryStream();
var writer = JsonReaderWriterFactory.CreateJsonWriter(
memoryStream, Encoding.UTF8, true, true, " ");
DataContractJsonSerializer ser = new DataContractJsonSerializer(serializableObject.GetType(), new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true });
ser.WriteObject(writer, serializableObject);
memoryStream.Position = 0;
StreamReader sr = new StreamReader(memoryStream);
return sr.ReadToEnd();
}
}

 

 

Login to Me Too
1 REPLY 1

sp8eu
Contributor
Contributor

Hi, Did you ever find a solution to this problem? I'm experiencing the same problem. I've seen other links in this forum on this topic and it looks like PayPal don't provide a solution that works. Their sample code looks like it's only suitable for desktop type apps.

Login to Me Too

Haven't Found your Answer?

It happens. Hit the "Login to Ask the community" button to create a question for the PayPal community.