WebApi Code
-------------------------------------------------------------------------------------------------------------------------
PayPalMethods.CS
public static class PayPalMethods
{
//private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/*
* Purpose: Gets the access token from PayPal
* Inputs: n/a
* Returns: access token
*
*/
public static string getAccessToken()
{
string serviceUrl = getServiceUrl("/v1/oauth2/token");
string clientId = getClientId();
string clientSecret = getClientSecret();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));
httpWebRequest.Headers["AcceptLanguage"] = "en_US";
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "POST";
string post = "grant_type=client_credentials";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(post);
streamWriter.Flush();
streamWriter.Close();
}
var result = "";
string accessToken = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Request: " + post + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
JObject o = JObject.Parse(result);
accessToken = (string)o["access_token"];
return accessToken;
}
/*
* Purpose: Gets the PayPal approval URL to redirect the user to.
*
* Inputs: access_token (The access token received from PayPal)
* Returns: approval URL
*/
public static string getApprovalUrl(string accessToken, string jsonRequest)
{
string serviceUrl = getServiceUrl("/v1/payments/payment");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonRequest);
streamWriter.Flush();
streamWriter.Close();
}
var result = "";
var approvalUrl = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
JObject o = JObject.Parse(result);
// parse out the approval_url link
foreach (var link in o["links"])
{
if ((string)link["rel"] == "approval_url")
{
approvalUrl = (string)link["href"];
}
}
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Request: " + jsonRequest + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
return approvalUrl;
}
/*
* Purpose: Executes the previously created payment for a given paymentID for a specific user's payer id.
*
* Inputs: paymentID (The id of the previously created PayPal payment)
* payerID (The id of the user received from PayPal)
* transactionAmountArray (amount array if updating the payment amount)
* Returns: Tuple (pair) containing
* - http statuscode (int)
* - json response object of the executed payment (JObject)
*/
public static Tuple<int, JObject> doPayment(string accessToken, string paymentID, string payerID, string jsonUpdate = null)
{
string serviceUrl = getServiceUrl("/v1/payments/payment/" + paymentID + "/execute");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "POST";
string jsonRequest = "";
JObject requestObject = null;
if (string.IsNullOrEmpty(jsonUpdate) == true)
{
requestObject = new JObject(
new JProperty(
"payer_id", payerID
)
);
jsonRequest = requestObject.ToString();
}
// update shipping: include "transactions" object that only contains "amount" object
else
{
JObject updateObject = JObject.Parse(jsonUpdate);
requestObject = new JObject(
new JProperty(
"payer_id", payerID
),
new JProperty(
"transactions", new JArray(
new JObject(
new JProperty(
"amount", updateObject
)
)
)
)
);
jsonRequest = requestObject.ToString();
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonRequest);
streamWriter.Flush();
streamWriter.Close();
}
string result = "";
int httpStatusCode = 0;
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
httpStatusCode = (int)httpResponse.StatusCode;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
httpStatusCode = (int)statusCode;
//log.Info("Server returned HTTP " + (int)statusCode + " (" + statusCode.ToString() + ")");
using (WebResponse wResponse = (HttpWebResponse)ex.Response)
{
using (Stream data = wResponse.GetResponseStream())
{
result = new StreamReader(data).ReadToEnd();
}
}
}
}
catch (Exception ex)
{
//log.Info(
// "Error: " + ex
//);
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Request: " + jsonRequest + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
JObject o = JObject.Parse(result);
Tuple<int, JObject> resultPair = new Tuple<int, JObject>(httpStatusCode, o);
return resultPair;
}
/*
* Purpose: Look up a payment resource, to get details about payments that have not yet been completed
*
* Inputs: paymentID (The id of the created payment)
* Returns: json response object
*/
public static JObject lookUpPaymentDetails(string accessToken, string paymentID)
{
string serviceUrl = getServiceUrl("/v1/payments/payment/" + paymentID);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "GET";
//Get Response
HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
JObject o = JObject.Parse(result);
return o;
}
/*
* Purpose: Create a csrf token used for better security
* Inputs: n/a
* Returns: csrf token (for use in forms and session)
*
*/
public static string getCsrfToken()
{
Random rnd = new Random();
Byte[] b = new Byte[32];
rnd.NextBytes(b);
string csrfToken = BitConverter.ToString(b);
csrfToken = csrfToken.Replace("-", "");
return csrfToken;
}
public static string getServiceUrl(string pathService)
{
bool sandboxFlag = Boolean.Parse(ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));
string serviceUrl = sandboxFlag ?
System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_ENDPOINT") + pathService :
System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_ENDPOINT") + pathService;
return serviceUrl;
}
public static string getClientId()
{
bool sandboxFlag = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));
string clientId = sandboxFlag ?
System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_CLIENT_ID") :
System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_CLIENT_ID");
return clientId;
}
public static string getClientSecret()
{
bool sandboxFlag = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));
string clientSecret = sandboxFlag ?
System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_CLIENT_SECRET") :
System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_CLIENT_SECRET");
return clientSecret;
}
}
-------------------------------------------------------------------------------------------------------------------------
PayPalObjects.CS
public class PayPalApi
{
public string name{ get; set; }
public string message { get; set; }
public string link{ get; set; }
public string addressLines { get; set; }
public string paymentID { get; set; }
public string paymentState { get; set; }
public string finalAmount { get; set; }
public string currency { get; set; }
public string transactionID { get; set; }
public string payerFirstName { get; set; }
public string payerLastName { get; set; }
public string recipientName { get; set; }
public string addressLine1 { get; set; }
public string addressLine2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postalCode { get; set; }
public string countryCode { get; set; }
}
public class PayPalObjects
{
public class Details
{
public string shipping { get; set; }
public string subtotal { get; set; }
public string tax { get; set; }
public string insurance { get; set; }
public string handling_fee { get; set; }
public string shipping_discount { get; set; }
}
public class Amount
{
public string currency { get; set; }
public string total { get; set; }
public Details details { get; set; }
}
public class Item
{
public string name { get; set; }
public string quantity { get; set; }
public string price { get; set; }
public string sku { get; set; }
public string currency { get; set; }
}
public class ItemList
{
public IList<Item> items { get; set; }
}
public class ShippingAddress
{
public string recipient_name { get; set; }
public string line1 { get; set; }
public string line2 { get; set; }
public string city { get; set; }
public string state { get; set; }
//public string phone { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
}
public class ItemListWithShipping
{
public IList<Item> items { get; set; }
public ShippingAddress shipping_address { get; set; }
}
public class Transaction
{
public Amount amount { get; set; }
public string description { get; set; }
public ItemList item_list { get; set; }
}
public class TransactionWithShipping
{
public Amount amount { get; set; }
public string description { get; set; }
public string custom { get; set; }
public ItemListWithShipping item_list { get; set; }
}
public class Payer
{
public string payment_method { get; set; }
}
public class RedirectUrls
{
public string cancel_url { get; set; }
public string return_url { get; set; }
}
// two root classes
public class ExpressCheckoutPaymentData
{
public IList<Transaction> transactions { get; set; }
public Payer payer { get; set; }
public string intent { get; set; }
public RedirectUrls redirect_urls { get; set; }
public ExpressCheckoutPaymentData(string cancelUrl, string placeOrderUrl)
{
intent = "sale";
payer = new PayPalObjects.Payer
{
payment_method = "paypal"
};
redirect_urls = new PayPalObjects.RedirectUrls
{
cancel_url = cancelUrl,
return_url = placeOrderUrl
};
transactions = new List<PayPalObjects.Transaction>
{
new PayPalObjects.Transaction
{
amount = new PayPalObjects.Amount
{
currency = "USD",
total = "0",
details = new PayPalObjects.Details
{
shipping = "0",
subtotal = "0",
tax = "0",
insurance = "0",
handling_fee = "0",
shipping_discount = "0"
}
},
description = "creating a payment",
item_list = new PayPalObjects.ItemList
{
items = new List<PayPalObjects.Item>
{
new PayPalObjects.Item
{
name = "Camera",
quantity = "1",
price = "0",
sku = "1",
currency = "USD"
}
}
}
}
};
}
}
public class ExpressCheckoutShippingPaymentData
{
public IList<TransactionWithShipping> transactions { get; set; }
public Payer payer { get; set; }
public string intent { get; set; }
public RedirectUrls redirect_urls { get; set; }
// constructor
public ExpressCheckoutShippingPaymentData(string cancelUrl, string payUrl)
{
intent = "sale";
payer = new PayPalObjects.Payer
{
payment_method = "paypal"
};
redirect_urls = new PayPalObjects.RedirectUrls
{
cancel_url = cancelUrl,
return_url = payUrl
};
transactions = new List<PayPalObjects.TransactionWithShipping>
{
new PayPalObjects.TransactionWithShipping
{
amount = new PayPalObjects.Amount
{
currency = "USD",
total = "0",
details = new PayPalObjects.Details
{
shipping = "0",
subtotal = "0",
tax = "0",
insurance = "0",
handling_fee = "0",
shipping_discount = "0"
}
},
description = "Creating a payment",
custom = "",
item_list = new PayPalObjects.ItemListWithShipping
{
items = new List<PayPalObjects.Item>
{
new PayPalObjects.Item
{
name = "Camera",
quantity = "1",
price = "0",
sku = "1",
currency = "USD"
}
},
shipping_address = new PayPalObjects.ShippingAddress {
recipient_name = "",
line1 = "",
line2 = "",
city = "",
state = "",
postal_code = "",
country_code = ""
}
}
}
};
}
}
}
------------------------------------------------------------------------------------------------------------------------
HomeController
public class HomeController : Controller
{
UnitOfWork uow = new UnitOfWork();
protected string accessToken;
protected string approvalUrl;
protected string requestCsrf;
protected string shippingFlowFlag;
protected JObject jsonResponse;
protected string paymentID;
protected string paymentState;
protected string finalAmount;
protected string currency;
protected string transactionID;
protected string payerFirstName;
protected string payerLastName;
protected string recipientName;
protected string addressLine1;
protected string addressLine2;
protected string city;
protected string state;
protected string postalCode;
protected string countryCode;
protected string addressLines;
public ActionResult PayPal(string total, int UserId)
{
AbleContext.Current.UserId = UserId;
var usersRepository = uow.Repository<UsersRepository>();
var userData = usersRepository.GetUserById(UserId);
var user = UserDataSource.LoadForUserName(userData.UserName);
var address = user.Addresses.Where(x => x.IsBilling == true).FirstOrDefault();
accessToken = PayPalMethods.getAccessToken();
Session["accessToken"] = accessToken;
Session["UserData"] = new CardModel { userId = UserId, Amount = Convert.ToDecimal(total) };
var hostName = Request.ServerVariables["HTTP_HOST"];
var appName = String.IsNullOrEmpty(Request.ServerVariables["REQUEST_URI"].Split('/')[0]) ? "" : Request.ServerVariables["REQUEST_URI"].Split('/')[0] + "/";
var cancelUrl = "http://" + hostName + "/Home/PaymentClose";
var payUrl = "http://" + hostName + "/Home/Pay";
var placeOrderUrl = "http://" + hostName + "/Home/PaymentError";
// JSON data for REST API calls.
// Session["expressCheckoutPaymentData"] is used in the PayPal Check Out flow
PayPalObjects.ExpressCheckoutPaymentData expressCheckoutPaymentData = new PayPalObjects.ExpressCheckoutPaymentData(cancelUrl, placeOrderUrl);
string expressCheckoutPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutPaymentData, Formatting.Indented);
Session["expressCheckoutPaymentData"] = expressCheckoutPaymentDataJson;
// Session["expressCheckoutShippingPaymentData"] is used for the Proceed to Checkout flow
PayPalObjects.ExpressCheckoutShippingPaymentData expressCheckoutShippingPaymentData = new PayPalObjects.ExpressCheckoutShippingPaymentData(cancelUrl, payUrl);
string expressCheckoutShippingPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutShippingPaymentData, Formatting.Indented);
Session["expressCheckoutShippingPaymentData"] = expressCheckoutShippingPaymentDataJson;
// session jason string converted to ExpressCheckoutShippingPaymentData object
PayPalObjects.ExpressCheckoutShippingPaymentData deserializedEcShipping = JsonConvert.DeserializeObject<PayPalObjects.ExpressCheckoutShippingPaymentData>(Session["expressCheckoutShippingPaymentData"].ToString());
// update fields based on form selections
deserializedEcShipping.transactions[0].amount.total = total;
deserializedEcShipping.transactions[0].amount.details.shipping = "0";
deserializedEcShipping.transactions[0].item_list.items[0].price = total;
deserializedEcShipping.transactions[0].amount.details.subtotal = total;
deserializedEcShipping.transactions[0].item_list.shipping_address.recipient_name = address.FirstName + " " + address.LastName;
deserializedEcShipping.transactions[0].item_list.shipping_address.line1 = address.Address1;
deserializedEcShipping.transactions[0].item_list.shipping_address.line2 = address.Address2;
deserializedEcShipping.transactions[0].item_list.shipping_address.city = address.City;
deserializedEcShipping.transactions[0].item_list.shipping_address.country_code = address.CountryCode;
deserializedEcShipping.transactions[0].item_list.shipping_address.postal_code = address.PostalCode;
deserializedEcShipping.transactions[0].item_list.shipping_address.state = address.Province;
// convert the modified Object back to JSON
string expressCheckoutFlowPaymentDataJson = JsonConvert.SerializeObject(deserializedEcShipping, Formatting.Indented);
Session["expressCheckoutFlowPaymentData"] = expressCheckoutFlowPaymentDataJson;
approvalUrl = PayPalMethods.getApprovalUrl(accessToken, expressCheckoutFlowPaymentDataJson) + "&useraction=commit"; // "Pay Now" button label
Session["approvalUrl"] = approvalUrl;
//return View();
return Redirect(approvalUrl);
}
public ActionResult Pay()
{
// Proceed to Checkout flow
if (Request.QueryString["paymentId"] != null && Request.QueryString["PayerID"] != null)
{
var doPaymentResponse = PayPalMethods.doPayment(Session["accessToken"].ToString(), Request.QueryString["paymentId"], Request.QueryString["PayerID"]);
int httpStatusCode = doPaymentResponse.Item1;
jsonResponse = doPaymentResponse.Item2;
// error
if (httpStatusCode != 200)
{
Session["error"] = jsonResponse;
return View("PaymentError");
}
}
// Express checkout flow
else
{
// session JSON string converted to ExpressCheckoutPaymentData object
PayPalObjects.ExpressCheckoutPaymentData deserializedEC = JsonConvert.DeserializeObject<PayPalObjects.ExpressCheckoutPaymentData>(Session["expressCheckoutPaymentData"].ToString());
// update object fields based on form selections
deserializedEC.transactions[0].amount.total = deserializedEC.transactions[0].amount.total.ToString();
deserializedEC.transactions[0].amount.details.shipping = Request.Form["shipping_method"].ToString();
string expressCheckoutPaymentUpdateDataJson = JsonConvert.SerializeObject(deserializedEC.transactions[0].amount, Formatting.Indented);
var doPaymentResponse = PayPalMethods.doPayment(Session["accessToken"].ToString(), Session["paymentId"].ToString(), Session["PayerID"].ToString(), expressCheckoutPaymentUpdateDataJson);
int httpStatusCode = doPaymentResponse.Item1;
jsonResponse = doPaymentResponse.Item2;
// error
if (httpStatusCode != 200)
{
Session["error"] = jsonResponse;
return View("PaymentError");
}
}
PayPalApi payPalApi = new PayPalApi();
payPalApi.paymentID = jsonResponse["id"].ToString();
payPalApi.paymentState = jsonResponse["state"].ToString();
payPalApi.finalAmount = jsonResponse["transactions"][0]["amount"]["total"].ToString();
payPalApi.currency = jsonResponse["transactions"][0]["amount"]["currency"].ToString();
payPalApi.transactionID = jsonResponse["transactions"][0]["related_resources"][0]["sale"]["id"].ToString();
payPalApi.payerFirstName = jsonResponse["payer"]["payer_info"]["first_name"].ToString();
payPalApi.payerLastName = jsonResponse["payer"]["payer_info"]["last_name"].ToString();
payPalApi.recipientName = jsonResponse["payer"]["payer_info"]["shipping_address"]["recipient_name"].ToString();
payPalApi.addressLine1 = jsonResponse["payer"]["payer_info"]["shipping_address"]["line1"].ToString();
payPalApi.addressLine2 = (jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"] != null) ? jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"].ToString() : "";
payPalApi.city = jsonResponse["payer"]["payer_info"]["shipping_address"]["city"].ToString();
payPalApi.state = jsonResponse["payer"]["payer_info"]["shipping_address"]["state"].ToString();
payPalApi.postalCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["postal_code"].ToString();
payPalApi.countryCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["country_code"].ToString();
// format address lines so no blank line
List<string> addr = new List<string>();
if (addressLine1 != "")
addr.Add(addressLine1);
if (addressLine2 != "")
addr.Add(addressLine2);
addressLines = string.Join("<br />", addr);
Session.Abandon();
return View(payPalApi);
}
[HttpGet]
public ActionResult PaymentError()
{
PayPalApi payPalApi = new PayPalApi();
JObject o = JObject.Parse(Session["error"].ToString());
if (o["name"] != null)
{
payPalApi.name = o["name"].ToString();
}
if (o["message"] != null)
{
payPalApi.message = o["message"].ToString();
}
if (o["information_link"] != null)
{
payPalApi.link = o["information_link"].ToString();
}
return View();
}
[HttpGet]
public ActionResult PaymentClose()
{
return View();
}
[HttpGet]
public ActionResult PaymentSuccess(CardModel cardModel)
{
//Your logic to save data in database
var result = new DataController().PayWithPayPal(cardModel);
return View();
}
}
------------------------------------------------------------------------------------------------------------------------
Views
PayPal.cshtml - default blank
Pay.cshtml -
@model Entity.PayPalApi
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<title>Pay</title>
</head>
<body>
<div class="container-fluid">
<div class="well" style="width:100% !important">
<h2 class="text-center">Payment Successfull</h2>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4" style="text-align:center !important">
<h3>
@Model.payerFirstName @Model.payerLastName , thank you for your Order!
</h3>
<br /><br />
<h4>
Shipping Address:
</h4>
<strong>
@Model.recipientName
</strong><br />
@Model.addressLines <br />
@Model.city @Model.state @Model.postalCode <br />
@Model.countryCode
<br />
<br />
<h4>Payment ID: <small>@Model.paymentID </small></h4>
<h4>Transaction ID: <small>@Model.transactionID </small></h4>
<h4>State: <small>@Model.paymentState </small></h4>
<h4>Total Amount: <small>@Model.finalAmount @Model.currency </small></h4>
<br />
<br />
@Html.ActionLink("Close", "PaymentSuccess", "Home", (Entity.CardModel)Session["UserData"] , null)
</div>
<div class="col-md-4"></div>
</div>
<!----- footer below ---->
</div>
</body>
</html>
PaymentClose.cshtml - Default
PaymentSuccess.cshtml - Default
--------------------------------------------------------------------------------------------------------------------------
Web.Config -
<appSettings>
<!-- Whether Sandbox environment is being used, Keep it true for testing -->
<add key="SANDBOX_FLAG" value="true" />
<!-- PayPal REST API endpoints -->
<add key="SANDBOX_ENDPOINT" value="https://api.sandbox.paypal.com" />
<add key="LIVE_ENDPOINT" value="https://api.paypal.com" />
<!-- Merchant ID -->
<add key="MERCHANT_ID" value="E9GCL5FX4TU2C" />
<!-- PayPal REST App SANDBOX Client Id and Client Secret -->
<add key="SANDBOX_CLIENT_ID" value="AZ8zBvPlgv_eqrYmOwHbjpevGrjY0ok8mPfrJ1Jhh2nuMN9awOZCpai9-yTWO2XEIpHTuyfoPWY_eTd5" />
<add key="SANDBOX_CLIENT_SECRET" value="EDi020P7EBhlJo_sv80jPcKIN0k-HSCEX07Eac37h-B9thGVpK7d_qFusYVVu9DNl3emGk2EgO_wYOkR" />
<!-- Environments -Sandbox and Production/Live -->
<add key="SANDBOX_ENV" value="sandbox" />
<add key="LIVE_ENV" value="production" />
<!-- PayPal REST App SANDBOX Client Id and Client Secret -->
<add key="LIVE_CLIENT_ID" value="your id" />
<add key="LIVE_CLIENT_SECRET" value="your secret" />
<!-- ButtonSource Tracker Code -->
<add key="SBN_CODE" value="PP-DemoPortal-EC-IC-csharp-REST" />
</appSettings>
Javascript
-------------------------------------------------------------------------------------------------------------------------
$scope.openInAppBrowserBlank = function (url) {
$ionicLoading.show();
var defaultOptions = {
location: 'no',
clearcache: 'no',
toolbar: 'no'
};
$cordovaInAppBrowser.open(url, '_blank', defaultOptions);
$rootScope.$on('$cordovaInAppBrowser:loadstart', function (e, event) {
var urlSuccessPage = HealthCareCommon.LocalHost() + "Home/PaymentSuccess";
var urlCancelPage = HealthCareCommon.LocalHost() + "Home/PaymentClose";
if (event.url.contains(urlSuccessPage)) {
$cordovaInAppBrowser.close();
$scope.ResetHome();
$state.go('app.orderComplete', { completeId: 3 });
}
else if (event.url.contains(urlCancelPage)) {
$cordovaInAppBrowser.close();
}
});
$rootScope.$on('$cordovaInAppBrowser:loadstop', function (e, event) {
});
$timeout(function () { $ionicLoading.hide() }, 2000);
}
-------------------------------------------------------------------------------------------------------------------------
PayPalMethods.CS
public static class PayPalMethods
{
//private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/*
* Purpose: Gets the access token from PayPal
* Inputs: n/a
* Returns: access token
*
*/
public static string getAccessToken()
{
string serviceUrl = getServiceUrl("/v1/oauth2/token");
string clientId = getClientId();
string clientSecret = getClientSecret();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(clientId + ":" + clientSecret));
httpWebRequest.Headers["AcceptLanguage"] = "en_US";
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "POST";
string post = "grant_type=client_credentials";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(post);
streamWriter.Flush();
streamWriter.Close();
}
var result = "";
string accessToken = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Request: " + post + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
JObject o = JObject.Parse(result);
accessToken = (string)o["access_token"];
return accessToken;
}
/*
* Purpose: Gets the PayPal approval URL to redirect the user to.
*
* Inputs: access_token (The access token received from PayPal)
* Returns: approval URL
*/
public static string getApprovalUrl(string accessToken, string jsonRequest)
{
string serviceUrl = getServiceUrl("/v1/payments/payment");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonRequest);
streamWriter.Flush();
streamWriter.Close();
}
var result = "";
var approvalUrl = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
JObject o = JObject.Parse(result);
// parse out the approval_url link
foreach (var link in o["links"])
{
if ((string)link["rel"] == "approval_url")
{
approvalUrl = (string)link["href"];
}
}
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Request: " + jsonRequest + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
return approvalUrl;
}
/*
* Purpose: Executes the previously created payment for a given paymentID for a specific user's payer id.
*
* Inputs: paymentID (The id of the previously created PayPal payment)
* payerID (The id of the user received from PayPal)
* transactionAmountArray (amount array if updating the payment amount)
* Returns: Tuple (pair) containing
* - http statuscode (int)
* - json response object of the executed payment (JObject)
*/
public static Tuple<int, JObject> doPayment(string accessToken, string paymentID, string payerID, string jsonUpdate = null)
{
string serviceUrl = getServiceUrl("/v1/payments/payment/" + paymentID + "/execute");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "POST";
string jsonRequest = "";
JObject requestObject = null;
if (string.IsNullOrEmpty(jsonUpdate) == true)
{
requestObject = new JObject(
new JProperty(
"payer_id", payerID
)
);
jsonRequest = requestObject.ToString();
}
// update shipping: include "transactions" object that only contains "amount" object
else
{
JObject updateObject = JObject.Parse(jsonUpdate);
requestObject = new JObject(
new JProperty(
"payer_id", payerID
),
new JProperty(
"transactions", new JArray(
new JObject(
new JProperty(
"amount", updateObject
)
)
)
)
);
jsonRequest = requestObject.ToString();
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonRequest);
streamWriter.Flush();
streamWriter.Close();
}
string result = "";
int httpStatusCode = 0;
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
httpStatusCode = (int)httpResponse.StatusCode;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
httpStatusCode = (int)statusCode;
//log.Info("Server returned HTTP " + (int)statusCode + " (" + statusCode.ToString() + ")");
using (WebResponse wResponse = (HttpWebResponse)ex.Response)
{
using (Stream data = wResponse.GetResponseStream())
{
result = new StreamReader(data).ReadToEnd();
}
}
}
}
catch (Exception ex)
{
//log.Info(
// "Error: " + ex
//);
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Request: " + jsonRequest + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
JObject o = JObject.Parse(result);
Tuple<int, JObject> resultPair = new Tuple<int, JObject>(httpStatusCode, o);
return resultPair;
}
/*
* Purpose: Look up a payment resource, to get details about payments that have not yet been completed
*
* Inputs: paymentID (The id of the created payment)
* Returns: json response object
*/
public static JObject lookUpPaymentDetails(string accessToken, string paymentID)
{
string serviceUrl = getServiceUrl("/v1/payments/payment/" + paymentID);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers["Authorization"] = "Bearer " + accessToken;
httpWebRequest.Headers["PayPal-Partner-Attribution-Id"] = System.Configuration.ConfigurationManager.AppSettings.Get("SBN_CODE");
httpWebRequest.Method = "GET";
//Get Response
HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
string jsonResponse = JValue.Parse(result).ToString(Formatting.Indented);
//log4net.Config.XmlConfigurator.Configure();
//log.Info(
// "Service URL: " + serviceUrl + Environment.NewLine +
// "Response: " + Environment.NewLine + jsonResponse
//);
JObject o = JObject.Parse(result);
return o;
}
/*
* Purpose: Create a csrf token used for better security
* Inputs: n/a
* Returns: csrf token (for use in forms and session)
*
*/
public static string getCsrfToken()
{
Random rnd = new Random();
Byte[] b = new Byte[32];
rnd.NextBytes(b);
string csrfToken = BitConverter.ToString(b);
csrfToken = csrfToken.Replace("-", "");
return csrfToken;
}
public static string getServiceUrl(string pathService)
{
bool sandboxFlag = Boolean.Parse(ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));
string serviceUrl = sandboxFlag ?
System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_ENDPOINT") + pathService :
System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_ENDPOINT") + pathService;
return serviceUrl;
}
public static string getClientId()
{
bool sandboxFlag = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));
string clientId = sandboxFlag ?
System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_CLIENT_ID") :
System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_CLIENT_ID");
return clientId;
}
public static string getClientSecret()
{
bool sandboxFlag = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_FLAG"));
string clientSecret = sandboxFlag ?
System.Configuration.ConfigurationManager.AppSettings.Get("SANDBOX_CLIENT_SECRET") :
System.Configuration.ConfigurationManager.AppSettings.Get("LIVE_CLIENT_SECRET");
return clientSecret;
}
}
-------------------------------------------------------------------------------------------------------------------------
PayPalObjects.CS
public class PayPalApi
{
public string name{ get; set; }
public string message { get; set; }
public string link{ get; set; }
public string addressLines { get; set; }
public string paymentID { get; set; }
public string paymentState { get; set; }
public string finalAmount { get; set; }
public string currency { get; set; }
public string transactionID { get; set; }
public string payerFirstName { get; set; }
public string payerLastName { get; set; }
public string recipientName { get; set; }
public string addressLine1 { get; set; }
public string addressLine2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postalCode { get; set; }
public string countryCode { get; set; }
}
public class PayPalObjects
{
public class Details
{
public string shipping { get; set; }
public string subtotal { get; set; }
public string tax { get; set; }
public string insurance { get; set; }
public string handling_fee { get; set; }
public string shipping_discount { get; set; }
}
public class Amount
{
public string currency { get; set; }
public string total { get; set; }
public Details details { get; set; }
}
public class Item
{
public string name { get; set; }
public string quantity { get; set; }
public string price { get; set; }
public string sku { get; set; }
public string currency { get; set; }
}
public class ItemList
{
public IList<Item> items { get; set; }
}
public class ShippingAddress
{
public string recipient_name { get; set; }
public string line1 { get; set; }
public string line2 { get; set; }
public string city { get; set; }
public string state { get; set; }
//public string phone { get; set; }
public string postal_code { get; set; }
public string country_code { get; set; }
}
public class ItemListWithShipping
{
public IList<Item> items { get; set; }
public ShippingAddress shipping_address { get; set; }
}
public class Transaction
{
public Amount amount { get; set; }
public string description { get; set; }
public ItemList item_list { get; set; }
}
public class TransactionWithShipping
{
public Amount amount { get; set; }
public string description { get; set; }
public string custom { get; set; }
public ItemListWithShipping item_list { get; set; }
}
public class Payer
{
public string payment_method { get; set; }
}
public class RedirectUrls
{
public string cancel_url { get; set; }
public string return_url { get; set; }
}
// two root classes
public class ExpressCheckoutPaymentData
{
public IList<Transaction> transactions { get; set; }
public Payer payer { get; set; }
public string intent { get; set; }
public RedirectUrls redirect_urls { get; set; }
public ExpressCheckoutPaymentData(string cancelUrl, string placeOrderUrl)
{
intent = "sale";
payer = new PayPalObjects.Payer
{
payment_method = "paypal"
};
redirect_urls = new PayPalObjects.RedirectUrls
{
cancel_url = cancelUrl,
return_url = placeOrderUrl
};
transactions = new List<PayPalObjects.Transaction>
{
new PayPalObjects.Transaction
{
amount = new PayPalObjects.Amount
{
currency = "USD",
total = "0",
details = new PayPalObjects.Details
{
shipping = "0",
subtotal = "0",
tax = "0",
insurance = "0",
handling_fee = "0",
shipping_discount = "0"
}
},
description = "creating a payment",
item_list = new PayPalObjects.ItemList
{
items = new List<PayPalObjects.Item>
{
new PayPalObjects.Item
{
name = "Camera",
quantity = "1",
price = "0",
sku = "1",
currency = "USD"
}
}
}
}
};
}
}
public class ExpressCheckoutShippingPaymentData
{
public IList<TransactionWithShipping> transactions { get; set; }
public Payer payer { get; set; }
public string intent { get; set; }
public RedirectUrls redirect_urls { get; set; }
// constructor
public ExpressCheckoutShippingPaymentData(string cancelUrl, string payUrl)
{
intent = "sale";
payer = new PayPalObjects.Payer
{
payment_method = "paypal"
};
redirect_urls = new PayPalObjects.RedirectUrls
{
cancel_url = cancelUrl,
return_url = payUrl
};
transactions = new List<PayPalObjects.TransactionWithShipping>
{
new PayPalObjects.TransactionWithShipping
{
amount = new PayPalObjects.Amount
{
currency = "USD",
total = "0",
details = new PayPalObjects.Details
{
shipping = "0",
subtotal = "0",
tax = "0",
insurance = "0",
handling_fee = "0",
shipping_discount = "0"
}
},
description = "Creating a payment",
custom = "",
item_list = new PayPalObjects.ItemListWithShipping
{
items = new List<PayPalObjects.Item>
{
new PayPalObjects.Item
{
name = "Camera",
quantity = "1",
price = "0",
sku = "1",
currency = "USD"
}
},
shipping_address = new PayPalObjects.ShippingAddress {
recipient_name = "",
line1 = "",
line2 = "",
city = "",
state = "",
postal_code = "",
country_code = ""
}
}
}
};
}
}
}
------------------------------------------------------------------------------------------------------------------------
HomeController
public class HomeController : Controller
{
UnitOfWork uow = new UnitOfWork();
protected string accessToken;
protected string approvalUrl;
protected string requestCsrf;
protected string shippingFlowFlag;
protected JObject jsonResponse;
protected string paymentID;
protected string paymentState;
protected string finalAmount;
protected string currency;
protected string transactionID;
protected string payerFirstName;
protected string payerLastName;
protected string recipientName;
protected string addressLine1;
protected string addressLine2;
protected string city;
protected string state;
protected string postalCode;
protected string countryCode;
protected string addressLines;
public ActionResult PayPal(string total, int UserId)
{
AbleContext.Current.UserId = UserId;
var usersRepository = uow.Repository<UsersRepository>();
var userData = usersRepository.GetUserById(UserId);
var user = UserDataSource.LoadForUserName(userData.UserName);
var address = user.Addresses.Where(x => x.IsBilling == true).FirstOrDefault();
accessToken = PayPalMethods.getAccessToken();
Session["accessToken"] = accessToken;
Session["UserData"] = new CardModel { userId = UserId, Amount = Convert.ToDecimal(total) };
var hostName = Request.ServerVariables["HTTP_HOST"];
var appName = String.IsNullOrEmpty(Request.ServerVariables["REQUEST_URI"].Split('/')[0]) ? "" : Request.ServerVariables["REQUEST_URI"].Split('/')[0] + "/";
var cancelUrl = "http://" + hostName + "/Home/PaymentClose";
var payUrl = "http://" + hostName + "/Home/Pay";
var placeOrderUrl = "http://" + hostName + "/Home/PaymentError";
// JSON data for REST API calls.
// Session["expressCheckoutPaymentData"] is used in the PayPal Check Out flow
PayPalObjects.ExpressCheckoutPaymentData expressCheckoutPaymentData = new PayPalObjects.ExpressCheckoutPaymentData(cancelUrl, placeOrderUrl);
string expressCheckoutPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutPaymentData, Formatting.Indented);
Session["expressCheckoutPaymentData"] = expressCheckoutPaymentDataJson;
// Session["expressCheckoutShippingPaymentData"] is used for the Proceed to Checkout flow
PayPalObjects.ExpressCheckoutShippingPaymentData expressCheckoutShippingPaymentData = new PayPalObjects.ExpressCheckoutShippingPaymentData(cancelUrl, payUrl);
string expressCheckoutShippingPaymentDataJson = JsonConvert.SerializeObject(expressCheckoutShippingPaymentData, Formatting.Indented);
Session["expressCheckoutShippingPaymentData"] = expressCheckoutShippingPaymentDataJson;
// session jason string converted to ExpressCheckoutShippingPaymentData object
PayPalObjects.ExpressCheckoutShippingPaymentData deserializedEcShipping = JsonConvert.DeserializeObject<PayPalObjects.ExpressCheckoutShippingPaymentData>(Session["expressCheckoutShippingPaymentData"].ToString());
// update fields based on form selections
deserializedEcShipping.transactions[0].amount.total = total;
deserializedEcShipping.transactions[0].amount.details.shipping = "0";
deserializedEcShipping.transactions[0].item_list.items[0].price = total;
deserializedEcShipping.transactions[0].amount.details.subtotal = total;
deserializedEcShipping.transactions[0].item_list.shipping_address.recipient_name = address.FirstName + " " + address.LastName;
deserializedEcShipping.transactions[0].item_list.shipping_address.line1 = address.Address1;
deserializedEcShipping.transactions[0].item_list.shipping_address.line2 = address.Address2;
deserializedEcShipping.transactions[0].item_list.shipping_address.city = address.City;
deserializedEcShipping.transactions[0].item_list.shipping_address.country_code = address.CountryCode;
deserializedEcShipping.transactions[0].item_list.shipping_address.postal_code = address.PostalCode;
deserializedEcShipping.transactions[0].item_list.shipping_address.state = address.Province;
// convert the modified Object back to JSON
string expressCheckoutFlowPaymentDataJson = JsonConvert.SerializeObject(deserializedEcShipping, Formatting.Indented);
Session["expressCheckoutFlowPaymentData"] = expressCheckoutFlowPaymentDataJson;
approvalUrl = PayPalMethods.getApprovalUrl(accessToken, expressCheckoutFlowPaymentDataJson) + "&useraction=commit"; // "Pay Now" button label
Session["approvalUrl"] = approvalUrl;
//return View();
return Redirect(approvalUrl);
}
public ActionResult Pay()
{
// Proceed to Checkout flow
if (Request.QueryString["paymentId"] != null && Request.QueryString["PayerID"] != null)
{
var doPaymentResponse = PayPalMethods.doPayment(Session["accessToken"].ToString(), Request.QueryString["paymentId"], Request.QueryString["PayerID"]);
int httpStatusCode = doPaymentResponse.Item1;
jsonResponse = doPaymentResponse.Item2;
// error
if (httpStatusCode != 200)
{
Session["error"] = jsonResponse;
return View("PaymentError");
}
}
// Express checkout flow
else
{
// session JSON string converted to ExpressCheckoutPaymentData object
PayPalObjects.ExpressCheckoutPaymentData deserializedEC = JsonConvert.DeserializeObject<PayPalObjects.ExpressCheckoutPaymentData>(Session["expressCheckoutPaymentData"].ToString());
// update object fields based on form selections
deserializedEC.transactions[0].amount.total = deserializedEC.transactions[0].amount.total.ToString();
deserializedEC.transactions[0].amount.details.shipping = Request.Form["shipping_method"].ToString();
string expressCheckoutPaymentUpdateDataJson = JsonConvert.SerializeObject(deserializedEC.transactions[0].amount, Formatting.Indented);
var doPaymentResponse = PayPalMethods.doPayment(Session["accessToken"].ToString(), Session["paymentId"].ToString(), Session["PayerID"].ToString(), expressCheckoutPaymentUpdateDataJson);
int httpStatusCode = doPaymentResponse.Item1;
jsonResponse = doPaymentResponse.Item2;
// error
if (httpStatusCode != 200)
{
Session["error"] = jsonResponse;
return View("PaymentError");
}
}
PayPalApi payPalApi = new PayPalApi();
payPalApi.paymentID = jsonResponse["id"].ToString();
payPalApi.paymentState = jsonResponse["state"].ToString();
payPalApi.finalAmount = jsonResponse["transactions"][0]["amount"]["total"].ToString();
payPalApi.currency = jsonResponse["transactions"][0]["amount"]["currency"].ToString();
payPalApi.transactionID = jsonResponse["transactions"][0]["related_resources"][0]["sale"]["id"].ToString();
payPalApi.payerFirstName = jsonResponse["payer"]["payer_info"]["first_name"].ToString();
payPalApi.payerLastName = jsonResponse["payer"]["payer_info"]["last_name"].ToString();
payPalApi.recipientName = jsonResponse["payer"]["payer_info"]["shipping_address"]["recipient_name"].ToString();
payPalApi.addressLine1 = jsonResponse["payer"]["payer_info"]["shipping_address"]["line1"].ToString();
payPalApi.addressLine2 = (jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"] != null) ? jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"].ToString() : "";
payPalApi.city = jsonResponse["payer"]["payer_info"]["shipping_address"]["city"].ToString();
payPalApi.state = jsonResponse["payer"]["payer_info"]["shipping_address"]["state"].ToString();
payPalApi.postalCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["postal_code"].ToString();
payPalApi.countryCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["country_code"].ToString();
// format address lines so no blank line
List<string> addr = new List<string>();
if (addressLine1 != "")
addr.Add(addressLine1);
if (addressLine2 != "")
addr.Add(addressLine2);
addressLines = string.Join("<br />", addr);
Session.Abandon();
return View(payPalApi);
}
[HttpGet]
public ActionResult PaymentError()
{
PayPalApi payPalApi = new PayPalApi();
JObject o = JObject.Parse(Session["error"].ToString());
if (o["name"] != null)
{
payPalApi.name = o["name"].ToString();
}
if (o["message"] != null)
{
payPalApi.message = o["message"].ToString();
}
if (o["information_link"] != null)
{
payPalApi.link = o["information_link"].ToString();
}
return View();
}
[HttpGet]
public ActionResult PaymentClose()
{
return View();
}
[HttpGet]
public ActionResult PaymentSuccess(CardModel cardModel)
{
//Your logic to save data in database
var result = new DataController().PayWithPayPal(cardModel);
return View();
}
}
------------------------------------------------------------------------------------------------------------------------
Views
PayPal.cshtml - default blank
Pay.cshtml -
@model Entity.PayPalApi
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<title>Pay</title>
</head>
<body>
<div class="container-fluid">
<div class="well" style="width:100% !important">
<h2 class="text-center">Payment Successfull</h2>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4" style="text-align:center !important">
<h3>
@Model.payerFirstName @Model.payerLastName , thank you for your Order!
</h3>
<br /><br />
<h4>
Shipping Address:
</h4>
<strong>
@Model.recipientName
</strong><br />
@Model.addressLines <br />
@Model.city @Model.state @Model.postalCode <br />
@Model.countryCode
<br />
<br />
<h4>Payment ID: <small>@Model.paymentID </small></h4>
<h4>Transaction ID: <small>@Model.transactionID </small></h4>
<h4>State: <small>@Model.paymentState </small></h4>
<h4>Total Amount: <small>@Model.finalAmount @Model.currency </small></h4>
<br />
<br />
@Html.ActionLink("Close", "PaymentSuccess", "Home", (Entity.CardModel)Session["UserData"] , null)
</div>
<div class="col-md-4"></div>
</div>
<!----- footer below ---->
</div>
</body>
</html>
PaymentError.cshtml -
@model Entity.PayPalApi
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<title>Error</title>
</head>
<body>
<div class="container-fluid">
<div class="well">
<h2 class="text-center">Error</h2>
</div>
<!----- header above ---->
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<div class="alert alert-danger" role="alert">
<p class="text-center"><strong>The payment could not be completed.</strong></p>
</div>
<br />
<strong>Reason: </strong> @Model.name <br />
<br />
<strong>Message: </strong> @Model.message <br />
<br />
<br />
@Html.ActionLink("Close", "PaymentClose", "Home", null, null)
</div>
<div class="col-sm-3"></div>
</div>
<!----- footer below ---->
</div>
</body>
</html>
PaymentSuccess.cshtml - Default
--------------------------------------------------------------------------------------------------------------------------
Web.Config -
<appSettings>
<!-- Whether Sandbox environment is being used, Keep it true for testing -->
<add key="SANDBOX_FLAG" value="true" />
<!-- PayPal REST API endpoints -->
<add key="SANDBOX_ENDPOINT" value="https://api.sandbox.paypal.com" />
<add key="LIVE_ENDPOINT" value="https://api.paypal.com" />
<!-- Merchant ID -->
<add key="MERCHANT_ID" value="E9GCL5FX4TU2C" />
<!-- PayPal REST App SANDBOX Client Id and Client Secret -->
<add key="SANDBOX_CLIENT_ID" value="AZ8zBvPlgv_eqrYmOwHbjpevGrjY0ok8mPfrJ1Jhh2nuMN9awOZCpai9-yTWO2XEIpHTuyfoPWY_eTd5" />
<add key="SANDBOX_CLIENT_SECRET" value="EDi020P7EBhlJo_sv80jPcKIN0k-HSCEX07Eac37h-B9thGVpK7d_qFusYVVu9DNl3emGk2EgO_wYOkR" />
<!-- Environments -Sandbox and Production/Live -->
<add key="SANDBOX_ENV" value="sandbox" />
<add key="LIVE_ENV" value="production" />
<!-- PayPal REST App SANDBOX Client Id and Client Secret -->
<add key="LIVE_CLIENT_ID" value="your id" />
<add key="LIVE_CLIENT_SECRET" value="your secret" />
<!-- ButtonSource Tracker Code -->
<add key="SBN_CODE" value="PP-DemoPortal-EC-IC-csharp-REST" />
</appSettings>
Javascript
-------------------------------------------------------------------------------------------------------------------------
$scope.openInAppBrowserBlank = function (url) {
$ionicLoading.show();
var defaultOptions = {
location: 'no',
clearcache: 'no',
toolbar: 'no'
};
$cordovaInAppBrowser.open(url, '_blank', defaultOptions);
$rootScope.$on('$cordovaInAppBrowser:loadstart', function (e, event) {
var urlSuccessPage = HealthCareCommon.LocalHost() + "Home/PaymentSuccess";
var urlCancelPage = HealthCareCommon.LocalHost() + "Home/PaymentClose";
if (event.url.contains(urlSuccessPage)) {
$cordovaInAppBrowser.close();
$scope.ResetHome();
$state.go('app.orderComplete', { completeId: 3 });
}
else if (event.url.contains(urlCancelPage)) {
$cordovaInAppBrowser.close();
}
});
$rootScope.$on('$cordovaInAppBrowser:loadstop', function (e, event) {
});
$timeout(function () { $ionicLoading.hide() }, 2000);
}


1 comments:
If you are looking the latest solution of PayPal payment integration in ASP.NET & C# (Using Orders v2 REST API with PayPal JavaScript SDK, Server-side Integration), check the demo ---> https://techtolia.com/PayPal/
Reply