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?
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
protected void ChargePayment(object sender, EventArgs e)
{
StripeCustomer CurrentCustomer = GetCustomer();
if (CurrentCustomer == null)
{
return;
}
var myCharge = new StripeChargeCreateOptions();
myCharge.Currency = "dkk";
myCharge.CustomerId = CurrentCustomer.Id;
myCharge.Description = "KPHF Prorated Charge";
string key = "sk_test_P6GjMq1OVwmxZv5YNozAX6dY";
var chargeService = new StripeChargeService(key);
try
{
chargeService.Create(myCharge);
}
catch (StripeException ex)
{
exError.Text = ex.Message;
}
}
private StripeCustomer GetCustomer()
{
MembershipUser CurrentUser = Membership.GetUser();
var myCustomer = new StripeCustomerCreateOptions();
var myCustomer2 = new StripeCreditCardOptions();
myCustomer.Email = cMail.Text;
myCustomer2.TokenId = CreditCard.Text;
myCustomer2.ExpirationMonth = CardMonth.SelectedItem.Text;
myCustomer2.ExpirationYear = CardYear.SelectedItem.Text;
myCustomer2.Cvc = cvc.Text;
myCustomer.PlanId = "1";
var customerService = new StripeCustomerService("sk_test_P6GjMq1OVwmxZv5YNozAX6dY");
try
{
StripeCustomer result = customerService.Create(myCustomer);
return result;
}
catch (StripeException ex)
{
exError.Text = ex.Message;
return null;
}
After entering credit card info I do get customer created in the stripe system, but he's not being charged and I get following exception: "Cannot charge a customer that has no active card". Any help or tips?
you are not attaching the card with the customer. You have created the card object but not attached with the customer. Follow this syntax to add the card
var myCustomer = new StripeCustomerCreateOptions();
myCustomer.Email = "pork#email.com";
myCustomer.Description = "Johnny Tenderloin (pork#email.com)";
// setting up the card
myCustomer.SourceCard = new SourceCard()
{
Number = "4242424242424242",
ExpirationYear = "2022",
ExpirationMonth = "10",
Cvc = "1223" // optional
};
myCustomer.PlanId = *planId*; // only if you have a plan
myCustomer.TaxPercent = 20; // only if you are passing a plan, this tax percent will be added to the price.
myCustomer.Coupon = *couponId*; // only if you have a coupon
myCustomer.TrialEnd = DateTime.UtcNow.AddMonths(1); // when the customers trial ends (overrides the plan if applicable)
myCustomer.Quantity = 1; // optional, defaults to 1
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Create(myCustomer)
you can read more about it here stripe .net
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.
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 :)