Webservice error in kentico CMS after upgrade - c#

I have created a web service using Kentico CMS 8.0 I've upgraded the instance to 8.2. When I try to call methods from my web service I get error in screenshot.
This is my method:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string ProcessOrderGeneralDonation(Dictionary<string, object> request)
{
Dictionary<string, object> response;
ProcessDonationOrder(request, out response);
return JSONResponse(true, "Data Populated", response);
}
private void ProcessDonationOrder(Dictionary<string, object> request, out Dictionary<string, object> response, bool isChampionOfCare = false)
{
var dictionary = new Dictionary<string, object> { };
#region Customer
var customer = GetNewCustomerInfo(request);
var customerType = ValidationHelper.GetInteger(request["customer_type"], 0);
if (customerType == 2) //company
{
customer.CustomerCompany = ValidationHelper.GetString(request["customer_organization"], String.Empty);
}
CustomerInfoProvider.SetCustomerInfo(customer);
var country = CountryInfoProvider.GetCountryInfo(ValidationHelper.GetString(request["customer_country"], String.Empty).Replace(" ", ""));
//var state = StateInfoProvider.GetStateInfo(ValidationHelper.GetString(request["customer_province"], String.Empty));
// Create new address object
var customerAddress = GetNewCustomerAddressInfo(request, customer);
if (country != null)
customerAddress.AddressCountryID = country.CountryID;
// Create the address
AddressInfoProvider.SetAddressInfo(customerAddress);
customerAddress.SetValue("AddressPhone", ValidationHelper.GetString(request["customer_phone"], String.Empty));
customerAddress.SetValue("AddressStateOthers", ValidationHelper.GetString(request["customer_province"], String.Empty));
customerAddress.Update();
// Create order addresses from customer address
OrderAddressInfo orderBillingAddress = OrderAddressInfoProvider.CreateOrderAddressInfo(customerAddress);
OrderAddressInfo orderShippingAddress = OrderAddressInfoProvider.CreateOrderAddressInfo(customerAddress);
// Set the order addresses
OrderAddressInfoProvider.SetAddressInfo(orderBillingAddress);
OrderAddressInfoProvider.SetAddressInfo(orderShippingAddress);
#endregion
var guid = ValidationHelper.GetGuid(request["guid"], Guid.Empty);
string message;
#region Shopping Cart
//Get Product
var product = GetProductSKUInfo(guid, out message);
if (product == null)
{
response = null;
return;
}
//Get Shopping Cart
var cart = GetShoppingCart();
// Add item to cart object
var param = new ShoppingCartItemParameters(product.SKUID, 1)
{
ProductOptions = new List<ShoppingCartItemParameters>
{
new ShoppingCartItemParameters(ValidationHelper.GetInteger(request["designation_id"], 0), 1),
new ShoppingCartItemParameters(ValidationHelper.GetInteger(request["donation_amount_id"], 0), 1)
}
};
if (isChampionOfCare)
{
//Get Champions Of Care Option Id
var options = OptionCategoryInfoProvider.GetProductOptionCategories(product.SKUID, true, OptionCategoryTypeEnum.Text);
var opt = options.Tables[0].AsEnumerable().SingleOrDefault(x => x["CategoryName"].ToString().ToLower() == "coc");
if (opt != null)
{
var categoryId = ValidationHelper.GetInteger(opt["CategoryID"], 0);
var skuOpt = GetSKUOptions(product.SKUID, categoryId) as DataTable;
if (skuOpt != null)
{
var cocId = ValidationHelper.GetInteger(skuOpt.Rows[0]["SKUID"], 0);
var cocParam = new ShoppingCartItemParameters(cocId, 1)
{
Text = ValidationHelper.GetString(request["coc_text"], string.Empty)
};
param.ProductOptions.Add(cocParam);
}
}
}
ShoppingCartItemInfo cartItem = cart.SetShoppingCartItem(param);
cartItem.CartItemCustomData["other_amount"] = ValidationHelper.GetDouble(request["donation_other_amount"], 0);
cart.ShoppingCartCustomData["donation_type"] = "GEN";
// Save item to database
ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(cartItem);
cart.ShoppingCartBillingAddress = orderBillingAddress;
cart.ShoppingCartShippingAddress = orderShippingAddress;
cart.Customer = customer;
cart.Update();
ShoppingCartInfoProvider.SetOrder(cart);
dictionary.Add("order_id", cart.OrderId);
UpdateDonor(request, cart.OrderId);
if (EnablePurchase)
{
Receipt responseReceipt;
request.Add("product_sku", product.SKUID);
Purchase(request, cart, customer, customerAddress, out responseReceipt);
var paymentSuccessed = !responseReceipt.GetMessage().Contains("DECLINED");
if (paymentSuccessed)
{
//HandleOrderNotification(cart);
SendInvoiceEmail(cart.OrderId);
}
dictionary.Add("moneris_message", responseReceipt.GetMessage());
}
#endregion
response = dictionary;
}

I believe the issue is that JSONResponse() doesn't know how to serialize a Dictionary<string,object> to a valid JSON format.
Take a look at some of these answers to help you solve this problem. Most of them suggest using a JSON library like JSON.NET:
https://stackoverflow.com/a/6620173/2344773
https://stackoverflow.com/a/5597628/2344773

i have already added JSON.NET to my project and JSONResponse() function
private string JSONResponse(bool success, string message, object data = null)
{
var dictionary = new Dictionary<string, object> { { "success", success }, { "message", message }, { "data", data } };
return JsonConvert.SerializeObject(dictionary, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}

Related

How to inject a variable into every class or method in c#

I have the following code.
[HttpGet]
public async Task<List<TenantManagementWebApi.Entities.SiteCollection>> Get()
{
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant(tenantAdminUrl, tenant.Email, keyVaultHelper.SecretValue))
{
Tenant tenantOnline = new Tenant(context);
SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
context.Load(siteProps);
context.ExecuteQuery();
List<TenantManagementWebApi.Entities.SiteCollection> sites = new List<TenantManagementWebApi.Entities.SiteCollection>();
foreach (var site in siteProps)
{
if(site.Template.Contains("SITEPAGEPUBLISHING#0") || site.Template.Contains("GROUP#0"))
{
string strTemplate= default(string);
if(site.Template.Contains("SITEPAGEPUBLISHING#0"))
{
strTemplate = "CommunicationSite";
};
if (site.Template.Contains("GROUP#0"))
{
strTemplate = "Modern Team Site";
};
try
{
Guid id = Guid.NewGuid();
Entities.SiteCollection sc = new Entities.SiteCollection()
{
Id = id.ToString(),
Owner = site.Owner,
Template = strTemplate,
Title = site.Title,
Active = false,
Url = site.Url
};
var added = await siteCollectionStore.AddAsync(sc);
sites.Add(sc);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
return sites;
};
}
However the following lines, I am repeating them on every method:
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
I will have lots of API controllers on my project
Is there an easy way (not refactor as a method), to make my code cleaner and inject the variables I need without copying and pasting every single time?

C# : set default payment method in stripe

I am new in stripe, how can we set default payment method in stripe.
And can we pass cardId/sourceId to charge customer along with customerId.
Code:-
private static async Task<string> ChargeCustomer(string customerId)
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
And 1 more question, how to get charge-list, I am using below code but getting exception(conversion error):-
private IEnumerable<StripeCharge> GetChargeList()
{
var chargeService = new StripeChargeService();
return chargeService.List();
}
This is what I ended up doing. Not sure why Stripe Checkout didn't set the card for the subscription setup as the default. Anyway, this fires triggered from the payment_intent.succeeded web hook. Sure there is a better way, but...
var customerService = new CustomerService(Configs.STRIPE_SECRET_KEY);
var c = customerService.Get(pi.CustomerId);
if (!string.IsNullOrEmpty(c.InvoiceSettings.DefaultPaymentMethodId)) {
status = "already has default payment method, no action";
hsc = HttpStatusCode.OK;
return;
}
var paymentMethodService = new PaymentMethodService(Configs.STRIPE_SECRET_KEY);
var lopm = paymentMethodService.ListAutoPaging(options: new PaymentMethodListOptions {
CustomerId = pi.CustomerId,
Type = "card"
});
if (!lopm.Any()) {
status = "customer has no payment methods";
hsc = HttpStatusCode.BadRequest;
return;
}
var pm = lopm.FirstOrDefault();
customerService.Update(pi.CustomerId, options: new CustomerUpdateOptions {
InvoiceSettings = new CustomerInvoiceSettingsOptions {
DefaultPaymentMethodId = pm.Id
}
});
hsc = HttpStatusCode.OK;
return;
We can pass cardId/BankAccountId/TokenId/SourceId in SourceTokenOrExistingSourceId property of StripeChargeCreateOptions,
private static async Task<string> ChargeCustomer(string customerId, string cardId)
{
try
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId,
SourceTokenOrExistingSourceId = cardId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
catch(Exception ex)
{
return "";
}
}
To set/change default payment method:-
public void ChangeDefaultPayment(string customerId, string sourceId)
{
var myCustomer = new StripeCustomerUpdateOptions();
myCustomer.DefaultSource = sourceId;
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Update(customerId, myCustomer);
}
Still looking for how to get charge-list.

How to Update campaign in Bing Ads?

For Update campaign I am using this Code
public async Task<List<long?>> updateCampaign(Campaign campaign,string status)
{
try
{
campaign.Status = (CampaignStatus)(int)Enum.Parse(typeof(CampaignStatus), status);
var request = new UpdateCampaignsRequest
{
Campaigns = new Campaign[] { campaign },
CustomerId = "xxxxxx",
UserName = "something#outlook.com",
Password = "something#123",
ApplicationToken = "myApplicationToken",
CustomerAccountId = "123456",
DeveloperToken = "1234567890"
};
CampaignService = new ServiceClient<ICampaignManagementService>(_authorizationData);
CampaignService.RefreshOAuthTokensAutomatically = false;
var result = (await CampaignService.CallAsync((s, r) => s.UpdateCampaignsAsync(r), request));
if (result.TrackingId != null)
{
return result.CampaignIds.ToList();
}
else
{
return new List<long?>();
}
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
When I run this code, I got this error "Invalid client data. Check the SOAP fault details for more information"
thanks.
For updating the Campaign we can use "BulkServiceManager" for bulk updating of the campaign,you can use this service single campaign update also.
public async Task<List<long?>> updateCampaign(List<Campaign> campaigns)
{
try
{
var listBulkCampaign = new List<BulkCampaign>();
foreach (var campaign in campaigns)
{
var _bulkCampaign = new BulkCampaign()
{
Campaign = campaign
};
listBulkCampaign.Add(_bulkCampaign);
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(_authorizationData);
string fileName = bingCampaignUpdate.csv;
var campaigns = (await bulkServiceManager.UploadEntitiesAsync(new EntityUploadParameters
{
Entities = listBulkCampaign,
OverwriteResultFile = true,
ResultFileDirectory = FileDirectory,
ResultFileName = fileName,
ResponseMode = ResponseMode.ErrorsAndResults
})).OfType<BulkCampaign>().ToList();
return new List<long?>();
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
You have to download .csv report and update the Campaigns.
I hope it helps you

How to use Paypal Checkout Hosted pages for Credit Card payments in MVC C#

I am facing problem in implementing Credit Card payments using Paypal Checkout Hosted pages for Credit Card transactions.
This is my code for Paypal payments:
public ActionResult CreatePayment(string packageName)
{
#region check client balance
long clientid = Convert.ToInt64(Session["iClientId"]);
string newPaymentMethod = "PayPal";
ClientPackageInfo obj = new ClientPackageInfo();
obj = objPaymentHelper.CalculateNewPackage(packageName, clientid, newPaymentMethod);
#region current package descriptor for paypal display
var newPkg = db.Package.Where(cs => cs.PackageId == obj.newPackageId).SingleOrDefault();
string paypalDisplayDecription = "Package : "+newPkg.Name+", Price : "+newPkg.Price+", Payable : "+obj.paymentAmount+", Description : "+newPkg.Description;
#endregion
if (obj.IsPaymentNeeded == true)
{
#region paypal viewdata
var viewData = new PayPalViewData();
var guid = Guid.NewGuid().ToString();
var paymentInit = new PayPal.Api.Payments.Payment
{
intent = "authorize",
payer = new PayPal.Api.Payments.Payer
{
payment_method = "paypal"
},
transactions = new List<PayPal.Api.Payments.Transaction>
{
new PayPal.Api.Payments.Transaction
{
amount = new PayPal.Api.Payments.Amount
{
currency = "USD",
total = (obj.paymentAmount + 0.0 + 0.0).ToString(),
details = new PayPal.Api.Payments.Details
{
subtotal = obj.paymentAmount.ToString(),
tax = 0.0.ToString(),
shipping = 0.0.ToString()
}
},
description = paypalDisplayDecription,
},
},
redirect_urls = new PayPal.Api.Payments.RedirectUrls
{
return_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/payment/confirmed?id={0}", guid)),
cancel_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/payment/index?id={0}", guid)),
},
};
viewData.JsonRequest = JObject.Parse(paymentInit.ConvertToJson()).ToString(Newtonsoft.Json.Formatting.Indented);
#endregion
#region create payment
try
{
var abc = ConfigManager.Instance.GetProperties()["ClientID"];
var abcc = ConfigManager.Instance.GetProperties()["ClientSecret"];
var accessToken = new PayPal.OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
var apiContext = new PayPal.APIContext(accessToken);
var createdPayment = paymentInit.Create(apiContext);
var approvalUrl = createdPayment.links.ToArray().FirstOrDefault(f => f.rel.Contains("approval_url"));
if (approvalUrl != null)
{
Session.Add(guid, createdPayment.id);
return Redirect(approvalUrl.href);
}
viewData.JsonResponse = JObject.Parse(createdPayment.ConvertToJson()).ToString(Newtonsoft.Json.Formatting.Indented);
return View("Error", viewData);
}
catch (PayPalException ex)
{
viewData.ErrorMessage = ex.Message;
return View("Error", viewData);
}
#endregion
}
else
{
#region save client information
SaveClientInfo saveinfo = new SaveClientInfo();
saveinfo = objPaymentHelper.SaveInfo(obj);
if(saveinfo.isSuccessfull == true)
{
Session["message"] = "show";
return RedirectToAction("Index", "iClientPackageHistory");
}
else
{
return View("Error");
}
#endregion
}
#endregion
}
I am not able to find a way to use the Checkout hosted pages of Paypal. I have already generated the code snippet of Paypal to be used on my page. Kindly help me how can I make changes to this code to be able to use Paypal Checkout Hosted Pages using C# MVC.

Paypal Payment Invalid when redirecting with javascript?

I have a problem with Paypal SDK REST, ASP.NET MVC 5 (C#) and javascript redirection.
I'm creating all the required components (ItemList, Address, Details, Amount,...) to make a Payment object for Paypal (not using credit card, so FundingInstruments are empty). After it is created, I use a View with a JavaScript Redirection to the URL Payment object has given to me. But everytime I see a 'Transaction is not valid...'
But, If I copy/Paste the URL ("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=...") to my browser MANUALLY, it works ! I'm going crazy...
Please have you got a solution ? (Find Enclosed the c# file, the payment in json format and the small html redirection component)
C# Payment Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PayPal;
using PayPal.Api;
using System.Configuration;
using System.Threading;
namespace WizziqWebApp.Paypal
{
public class PaymentService
{
public enum EPaymentMethod { Paypal, CreditCard };
public static readonly Dictionary<EPaymentMethod, string> PaymentMethods = new Dictionary<EPaymentMethod, string>() {
{ EPaymentMethod.Paypal, "paypal" },
{ EPaymentMethod.CreditCard, "credit_card" }
};
private OAuthTokenCredential _authToken;
private APIContext _api;
public Payment CreatePayment(Models.OrderModel order, EPaymentMethod paymentMethod, string cancelUrl, string returnUrl)
{
ItemList itemList = CreateItemList(order.shoppingCart);
//itemList.shipping_address = (ShippingAddress) CreateDeliveryAddress(order.fullRegisterModel);
Address InvoicingAddress = CreateInvoiceAddress(order.fullRegisterModel);
Details details = CreatePaymentDetails(order.shoppingCart);
Amount amount = CreateAmount(order.shoppingCart, details);
Payer payer = null;
if (paymentMethod == EPaymentMethod.CreditCard)
{
CreditCard creditCard = CreateCreditCard(InvoicingAddress);
FundingInstrument fundingInstrument = CreateCreditCardFundingInstrument(creditCard);
List<FundingInstrument> lst = new List<FundingInstrument>();
lst.Add(fundingInstrument);
payer = CreatePayerCreditCard(lst);
}
else if (paymentMethod == EPaymentMethod.Paypal)
{
payer = CreatePayerPaypal();
}
var transactionList = new List<Transaction>();
Transaction transaction = CreateTransaction(amount, itemList, order);
transactionList.Add(transaction);
var payment = new Payment
{
transactions = transactionList,
intent = "sale",
payer = payer,
redirect_urls = new RedirectUrls
{
cancel_url = cancelUrl,
return_url = returnUrl
}
};
payment = payment.Create(this.Api);
System.IO.File.WriteAllText(#"d:\devel\PaymentObject.json",
payment.ConvertToJson());
return payment;
}
public Payment ConfirmPayment(string token, string payerId)
{
var paymentExecution = new PaymentExecution
{
payer_id = payerId
};
var payment = new Payment { id = token };
return payment.Execute(this.Api, paymentExecution);
}
private ItemList CreateItemList(Models.ShoppingCart Cart)
{
ItemList PaypalItemList = new ItemList();
List<Item> itms = new List<Item>();
if (Cart != null)
{
foreach (Models.ShoppingCartLine line in Cart.Lines)
{
Item item = new Item();
item.name = line.Product.ArticleId;
item.currency = line.Currency.ShortCode;
item.price = line.UnitPrice.ToString("0.00", Thread.CurrentThread.CurrentCulture);
item.quantity = Convert.ToString(line.Quantity);
item.sku = line.Product.ArticleId;
itms.Add(item);
}
}
PaypalItemList.items = itms;
return PaypalItemList;
}
private Address CreateInvoiceAddress(Models.FullRegisterModel model)
{
Address Address = null;
if (model != null && model.InvoicingAddress != null)
{
Address = new Address();
Address.city = model.InvoicingAddress.City;
Address.country_code = model.InvoicingAddress.Country;
Address.line1 = model.InvoicingAddress.StreetAddress;
Address.postal_code = model.InvoicingAddress.ZipCode;
Address.state = model.InvoicingAddress.State;
}
return Address;
}
private ShippingAddress CreateDeliveryAddress(Models.FullRegisterModel model)
{
ShippingAddress Address = null;
if (model != null && model.DeliveryAddress != null)
{
Address = new ShippingAddress();
Address.city = model.DeliveryAddress.City;
Address.country_code = model.DeliveryAddress.Country;
Address.line1 = model.DeliveryAddress.StreetAddress;
Address.postal_code = model.DeliveryAddress.ZipCode;
Address.state = model.DeliveryAddress.State;
Address.recipient_name = model.LastName + ", " + model.FirstName;
}
return Address;
}
private CreditCard CreateCreditCard(Address invoiceAddress)
{
CreditCard creditCard = null;
{
creditCard = new CreditCard();
creditCard.billing_address = invoiceAddress;
creditCard.cvv2 = "874"; //card cvv2 number
creditCard.expire_month = 4; //card expire date
creditCard.expire_year = 2020; //card expire year
creditCard.first_name = "Aman";
creditCard.last_name = "Thakur";
creditCard.number = "4032034438655220"; //enter your credit card number here
creditCard.type = "visa"; //credit card type here paypal allows 4 types
}
return creditCard;
}
private Details CreatePaymentDetails(Models.ShoppingCart Cart)
{
Details details = null;
if (Cart != null)
{
details = new Details();
details.shipping = Convert.ToString(Cart.DeliveryFee.Total);
details.subtotal = Convert.ToString(Cart.GetTotal());
details.tax = "0";
}
return details;
}
private Amount CreateAmount(Models.ShoppingCart Cart, Details details)
{
var total = Cart.GetTotal() + Cart.DeliveryFee.Total + Convert.ToDecimal(details.tax);
var amount = new Amount
{
currency = Cart.Currency.ShortCode,
details = details,
total = total.ToString()
};
return amount;
}
private Transaction CreateTransaction(Amount amount, ItemList itemList, Models.OrderModel model)
{
Transaction transaction = new Transaction();
if (amount != null && itemList != null)
{
transaction.amount = amount;
transaction.description = "WIZZIQ products";
transaction.invoice_number = Convert.ToString(model.OrderNumber);
transaction.item_list = itemList;
//transaction.notify_url = "";
//transaction.order_url = "";
}
return transaction;
}
private FundingInstrument CreateCreditCardFundingInstrument(CreditCard creditCard)
{
return new FundingInstrument()
{
credit_card = creditCard
};
}
private Payer CreatePayerCreditCard(List<FundingInstrument> listFundingInstruments)
{
Payer payer = new Payer();
if (listFundingInstruments != null)
{
payer.funding_instruments = listFundingInstruments;
payer.payment_method = PaymentMethods[EPaymentMethod.CreditCard];
}
return payer;
}
private Payer CreatePayerPaypal()
{
Payer payer = new Payer();
payer.payment_method = PaymentMethods[EPaymentMethod.Paypal];
return payer;
}
private OAuthTokenCredential ApiAccessToken
{
get
{
if (this._authToken != null)
{
return this._authToken;
}
var clientId = ConfigurationManager.AppSettings["clientId"];
var secretToken = ConfigurationManager.AppSettings["secretToken"];
var config = new Dictionary<string, string> { { "mode", "sandbox" } };
this._authToken = new OAuthTokenCredential(clientId, secretToken, config);
return this._authToken;
}
}
private APIContext Api
{
get
{
return this._api ?? (this._api = new APIContext(this.ApiAccessToken.GetAccessToken()));
}
}
}
}
HTML Redirection
#{
ViewBag.Title = "_Redirect";
Layout = "~/Views/Shared/Layout/_LayoutEmpty.cshtml";
}
<div class="jumbotron">
<div class="container">
<h1>Please wait...</h1>
<p>
<div class="popover-content">
<div class="loading-circle"></div>
<div class="loading-circle1"></div>
<div class="small-title clr-wizziq text-center"><span>While redirecting to Paypal...</span></div>
</div>
</p>
</div>
</div>
<script>
setTimeout(function () {
var url = '#ViewBag.RedirectUrl';
alert('Redirect to: ' + url);
window.location.href = url;
}, 1000);
</script>
JSON Payment
{
"id":"PAY-14N977666S5313604KWP4CGQ",
"intent":"sale",
"payer":{
"payment_method":"paypal",
"payer_info":{
"shipping_address":{
}
}
},
"transactions":[
{
"related_resources":[
],
"amount":{
"currency":"EUR",
"total":"18033.45",
"details":{
"subtotal":"18033.45"
}
},
"description":"WIZZIQ products",
"invoice_number":"4",
"item_list":{
"items":[
{
"quantity":"1",
"name":"IQREPAIRKIT",
"price":"1500.00",
"currency":"EUR",
"sku":"IQREPAIRKIT"
},
{
"quantity":"3",
"name":"IQBUR010",
"price":"9.20",
"currency":"EUR",
"sku":"IQBUR010"
},
{
"quantity":"1",
"name":"IQBUR016",
"price":"9.20",
"currency":"EUR",
"sku":"IQBUR016"
},
{
"quantity":"250",
"name":"IQREP20INJ",
"price":"49.90",
"currency":"EUR",
"sku":"IQREP20INJ"
},
{
"quantity":"1",
"name":"IQPOLISH",
"price":"3.75",
"currency":"EUR",
"sku":"IQPOLISH"
},
{
"quantity":"2",
"name":"IQTRANSFO",
"price":"8.95",
"currency":"EUR",
"sku":"IQTRANSFO"
},
{
"quantity":"5",
"name":"IQSTARTERKIT",
"price":"800.00",
"currency":"EUR",
"sku":"IQSTARTERKIT"
}
]
}
}
],
"state":"created",
"create_time":"2015-07-10T12:56:58Z",
"update_time":"2015-07-10T12:56:58Z",
"links":[
{
"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-14N977666S5313604KWP4CGQ",
"rel":"self",
"method":"GET"
},
{
"href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-4HC32806NW4529238",
"rel":"approval_url",
"method":"REDIRECT"
},
{
"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-14N977666S5313604KWP4CGQ/execute",
"rel":"execute",
"method":"POST"
}
]
}
Thank you very much ! I'm really stuck...
For the record, here's how I fixed it:
Ok, that was my fault, the redirection was not what I expected to be... To correct it, don't forget to put your URL from RAZOR in RAW mode :).
<script>
setTimeout(function () {
var url = '**#Html.Raw(Model.Url)**';
alert('Redirect to: ' + url);
window.location.href = url;
}, 1000);
</script>
Anyway, thanks to the Paypal team for trying to help but too late :)

Categories

Resources