API to stripe make 500 - c#

That's when i need to use the Stripe API so when i need it, it will go wrong and make mistakes in the Stripe area as you can see here.
i have : v15.6.1 on Stripe.net
Where it goes wrong is here:
planservice.Create(new StripePlanCreateOptions()
to here:
PlanId = abn.PriceValueUnikId };
all the value I get by json eg userid, pric and pricId there is content in them.
[HttpPost]
public IActionResult Post([FromBody] JObject token)
{
var api = Settings.ConstName.StrinpAPIKeyTest;
StripeConfiguration.SetApiKey(api);
var chargeService = new StripeChargeService();
chargeService.ExpandBalanceTransaction = true;
chargeService.ExpandCustomer = true;
chargeService.ExpandInvoice = true;
//StripeCharge stripeCharge = chargeService.Get(api);
var customerSerive = new StripeCustomerService(api);
var subservice = new StripeSubscriptionService(api);
var planservice = new StripePlanService(api);
var pricId = (int)token.GetValue("pricid");
var pric = (int)token.GetValue("pric");
var userid = (int) Userid();
var abn = _dbContext.PriceValue.FirstOrDefault(i => i.PriceValueId == pricId || i.Price == pric);
//Finder information omkring pakken til den enkelte pakke.
var currentUser = _dbContext.Users.FirstOrDefault(i => i.UserId == userid);
if (currentUser != null)
{
if (abn != null)
{
var orderid = Settings.ValueWordsAndNumbers.OrdreValue();//Orderid
var planType = $"OrderId: {orderid} - Pris: {abn.Price} - Mdr: {abn.Months} UserId: {userid}";
planservice.Create(new StripePlanCreateOptions()//error from here
{
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
Id = abn.PriceValueUnikId
});
var newCustomer = new StripeCustomerCreateOptions
{
SourceToken = token["id"].ToString(),
Email = token["email"].ToString(),
PlanId = abn.PriceValueUnikId,
};//error to here
var stripeCustomer = customerSerive.Create(newCustomer);
}
}

var planOptions = new StripePlanCreateOptions() {
Product = new StripePlanProductCreateOptions() {
Name = "planType"
},
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
};
var planService = new StripePlanService();
StripePlan plan = planService.Create(planOptions);

API version to 2018-02-06 and add support for Product & Plan API
Now Product is REQUIRED.
you need past ID product or dictionary containing fields used to create a service product.
var planOptions = new StripePlanCreateOptions() {
ProductId ="Product Plan id",
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
};

Related

How can I store multiple dynamic products in stripe checkout webforms (ASP.NET C#) I tried a lot but static it's worked but dynamic not?

here is the code:-
static I used its worked fine.. how can I store product dynamically in using asp.net c#
LineItems = new List<SessionLineItemOptions>
{
for (int i = 0; i < dtOrder.Rows.Count; i++){
new SessionLineItemOptions
{
Name=dtOrder.Rows[i]["ProductName"].toString(),
Currency="cad",
Amount =Convert.toInt64(dtOrder>Rows[i]["Price"])*100,
Quantity = 1,
},
}
},
Extending the snippet shown in the API reference here, we can replace Price = 'price_123' with PriceData (API ref) like so:
var options = new SessionCreateOptions
{
SuccessUrl = "https://example.com/success",
CancelUrl = "https://example.com/cancel",
PaymentMethodTypes = new List<string>
{
"card",
},
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
PriceData = new SessionLineItemPriceDataOptions
{
Currency = "usd",
UnitAmount = 50000,
ProductData = new SessionLineItemPriceDataProductDataOptions
{
Name = "some product name",
}
},
Quantity = 2,
},
},
Mode = "payment",
};
var service = new SessionService();
service.Create(options);
You can find all the type definitions in the source code.
I integrated Mulitple Account Payment of stripe and fixed the issue like this
and its working for me now , you can also use simple checkout method like this fetching dynamically product from db
List lineItemsOptions = new List();
string cmdText = "select * from tableorder where sessionid='"+ sessionid + "'";
DataSet ds = dbm.getDs(cmdText);
foreach (DataRow row in ds.Tables[0].Rows)
{
var currentLineItem = new SessionLineItemOptions
{
Name = row["ProductName"].ToString(),
Amount = 100,//Convert.ToInt32( row["variationPrice"].ToString()),
Currency = "usd",
Quantity = Convert.ToInt32(row["Quantity"].ToString()),
};
lineItemsOptions.Add(currentLineItem);
}
StripeConfiguration.ApiKey = ".......................................";
var options = new SessionCreateOptions();
options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string>
{
"card",
},
LineItems = lineItemsOptions,
PaymentIntentData = new SessionPaymentIntentDataOptions
{
ApplicationFeeAmount = 1,
},
Mode = "payment",
SuccessUrl = "https://www.......com/success.aspx",
CancelUrl = "https://example.com/cancel",
};
var requestOptions = new RequestOptions
{
StripeAccount = ".............",
};
var service = new SessionService();
Session session = service.Create(options, requestOptions);

Invoicer PDF gives null but Membership does not give PDF null

My problem as it is right now. It is that I must have made such that a customer can buy an item that is only paid once. Thus assigned Invoice id and PDf to the database.
As it is right now I only get hold of Invoice id while PDF is null.
I've read a little more about this.
Invoice Id return with null after change using Stripe
var options = new ProductCreateOptions
{
Name = "Starter Setup",
};
var service = new ProductService();
var product = service.Create(options);
var optionsA = new PriceCreateOptions
{
Product = product.Id,
UnitAmount = 2000,
Currency = "usd",
};
var serviceA = new PriceService();
var price = serviceA.Create(optionsA);
var optionsB = new CustomerCreateOptions
{
Email = model.Mail,
Name = model.FuldName,
Source = token
};
var serviceB = new CustomerService();
var customer = serviceB.Create(optionsB);
var optionsC = new InvoiceItemCreateOptions
{
Customer = customer.Id,
Price = price.Id,
};
var serviceC = new InvoiceItemService();
var invoiceItem = serviceC.Create(optionsC);
var invoiceId = invoiceItem.Id;
var serviceE = new InvoiceService();
var f = serviceE.Get(invoiceId);
var pdf = f.InvoicePdf;// This here gives zero.
If I do it this way, I'll get this out of it. I get the Invoice ID that I want here but I get nothing on the invoice that shows that it is zero.
{
"id": "ii_1IR4UtFnB7TvDVRrzPwWo8ZW",
"object": "invoiceitem",
"amount": 2000,
"currency": "usd",
"customer": "cus_J3Aqpyt4PwqCcN",
"date": 1614815575,
"description": "Starter Setup",
"discountable": true,
"discounts": [
],
"invoice": null,
"livemode": false,
"metadata": {
},
....
}
With this, my thinking is whether I will in a way be able to make such that I make a membership which then stops immediately but that it says in the invoice that the purchase is only of a single item and not several months.
The way I have done it in relation to membership I have done like this.
var createCustomer = new CustomerCreateOptions
{
Source = token,
Name = model.FuldName,
Email = model.Mail
};
var addService = new CustomerService();
var customer = addService.Create(createCustomer);
var optionsProduct = new ProductCreateOptions
{
Name = $"Single buy - {DateTime.Now} - Kursus Id : {id}",
Type = "service",
};
var serviceProduct = new ProductService();
Product product = serviceProduct.Create(optionsProduct);
var optionsPlan = new PlanCreateOptions
{
Currency = "dkk",
Interval = Helpers.Stripe.interval,
Nickname =
$"Single buy - {DateTime.Now} - Kursus Id : {id}",
Amount = amount,
Product = product.Id,
IntervalCount = 1
};
var servicePlan = new PlanService();
Plan plan = servicePlan.Create(optionsPlan);
var items = new List<SubscriptionItemOptions>()
{
new SubscriptionItemOptions()
{
Plan = plan.Id,
Quantity = 1
},
};
var createSubscruptionA = new SubscriptionCreateOptions
{
Customer = customer.Id,
Items = items,
OffSession = true,
};
var addserviceA = new SubscriptionService();
Subscription subscription = addserviceA.Create(createSubscruptionA);
var invoiceId = subscription.LatestInvoiceId;
var service = new InvoiceService();
var pdf = service.Get(invoiceId).InvoicePdf;
That which I would like to achieve by this. It is that I can get hold of PDF and Invoice id as I will use it for my system in the future etc.
EDIT
var optionsB = new CustomerCreateOptions
{
Email = model.Mail,
Name = model.FuldName,
Source = token
};
var serviceB = new CustomerService();
var customer = serviceB.Create(optionsB);
var optionsC = new InvoiceItemCreateOptions
{
Customer = customer.Id,
Price = price.Id,
};
var serviceC = new InvoiceItemService();
var invoiceItem = serviceC.Create(optionsC);
var invoiceId = invoiceItem.Id;
var invoiceOptions = new InvoiceCreateOptions
{
Customer = customer.Id,
AutoAdvance = true,
};
var invoiceService = new InvoiceService();
var invoice = invoiceService.Create(invoiceOptions);
For one-off Invoices you need to create Invoice Items for the Customer (as you've done), but importantly you then need to create an Invoice that will contain those Items.
This line is not correct for what you're trying to accomplish:
var invoiceId = invoiceItem.Id;
Instead, you need to create the invoice as shown in the docs linked above:
var invoiceOptions = new InvoiceCreateOptions
{
Customer = "cus_123",
AutoAdvance = true,
};
var invoiceService = new InvoiceService();
var invoice = invoiceService.Create(invoiceOptions);
The Invoice object will have an invoice_pdf URL (docs) after you finalize it.
var service = new InvoiceService();
service.FinalizeInvoice(
"in_123"
);

How can I fix this Error: not all code paths return a value

My project has 2 part ClientSide and Server side. In Server side I have Controller that it needs query and command. I put both of them and my command has a handler but after I'd done my handler it throws a error that say: not all code paths return a value.
this is my handler:
public Task<ReturnCreateDataQuery> Handle(CreateCompletedActCommand request, CancellationToken cancellationToken)
{
var party = _dbContext.Parties.SingleOrDefault(t => t.PartyCode == request.PartyCode);
if (party == null) throw new Exception("");
if ((bool)request.ResonableType)
{
var departmentText = request.DepartmentIds.Any() ? string.Join(",", request.DepartmentIds.Distinct().OrderBy(t => t)) : string.Empty;
var cartableActs = new List<CartableActModel>();
var cartable = new CartableStateModel()
{
ClaimId = request.ClaimId,
CreationDate = DateTime.Now,
StatusCode = (int)Enumeration.StateType.Compeleted,
PreviouseCartableStateId = request.CartableStateId
};
var cartableAct = new CartableActCompleteModel()
{
ActCode = (int)Enumeration.ActType.CompleteCustomerData,
ActorId = party.PartyId,
CartableStateId = cartable.CartableStateId,
ChangeDate = DateTime.Now,
ClaimSubjectId = request.ClaimSubjectId,
ClaimType = request.ClaimType,
Departments = departmentText,
ExpertPartyId = request.ExpertPartyId,
ResonableType = request.ResonableType,
SubClaimSubjectId = request.SubClaimSubjectId,
CompletedDescription = request.CompletedDescription,
};
var attachments = request.Attachments.Select(t => new ActAttachmentModel
{
AttachmentContent = t.AttachmentContent,
ActAttachmentId = cartableAct.CartableActId,
ActId = cartableAct.CartableActId,
CreationDate = DateTime.Now,
Creator = party.PartyId,
FileExtension = t.FileExtension,
Title = t.Title,
MimeType = t.MimeType
}).ToList();
cartableAct.ActAttachments = attachments;
cartableActs.Add(cartableAct);
cartable.CartableActs = cartableActs;
_dbContext.Cartables.Add(cartable);
_dbContext.SaveChangesAsync(cancellationToken);
}
else
{
var cartableActs = new List<CartableActModel>();
var cartable = new CartableStateModel()
{
ClaimId = request.ClaimId,
CreationDate = DateTime.Now,
StatusCode = (int)Enumeration.StateType.Finished,
};
var cartableAct = new CartableActSatisficationModel()
{
ActCode = (int)Enumeration.ActType.SatisficationCustomer,
ActorId = party.PartyId,
CartableStateId = cartable.CartableStateId,
ChangeDate = DateTime.Now,
IsSatisfy = false,
SatisfyLevel = "1",
};
var attachments = request.Attachments.Select(t => new ActAttachmentModel
{
AttachmentContent = t.AttachmentContent,
ActAttachmentId = cartableAct.CartableActId,
ActId = cartableAct.CartableActId,
CreationDate = DateTime.Now,
Creator = party.PartyId,
FileExtension = t.FileExtension,
Title = t.Title,
MimeType = t.MimeType
}).ToList();
var outBox = new OutBoxModel
{
SentType = "SMS",
ClaimId = request.ClaimId,
IsSent = false,
PartyCode = request.PartyCode,
IsCustomer = true
};
cartableAct.ActAttachments = attachments;
cartableActs.Add(cartableAct);
cartable.CartableActs = cartableActs;
_dbContext.Cartables.Add(cartable);
_dbContext.OutBoxes.Add(outBox);
_dbContext.SaveChangesAsync(cancellationToken);
}
}
I don't know how can I fix this error I search a lot of source but I can't understand which value should return if you know this I would thank you.
Change your metod header
public async Task Handle(CreateCompletedActCommand request, CancellationToken cancellationToken)
{
....your code
}

TimeActivity with .NET API v3 SDK

I can't get a time activity to save with the latest version of the .NET SDK and Quickbooks Online. I think it's the Employee Reference, but I just can't sort it out. Does the API even work right?
DataService commonService = new DataService(serviceContext);
string displayName = "Test Customer";
displayName = displayName.Replace("'", "\\'"); //Escape special characters
QueryService<Customer> customerQueryServiceXX = new QueryService<Customer>(serviceContext);
Customer resultCustomer = customerQueryServiceXX.Where(m => m.DisplayName == displayName).FirstOrDefault();
string employeeName = "First Last";
employeeName = employeeName.Replace("'", "\\'"); //Escape special characters
QueryService<Employee> customerQueryServiceEE = new QueryService<Employee>(serviceContext);
Employee resultEmployee = customerQueryServiceEE.Where(m => m.DisplayName == employeeName).FirstOrDefault();
string sfasdfasdfasdf = resultEmployee.FamilyName;
TimeActivity timeActivity = new TimeActivity();
timeActivity.BillableStatus = BillableStatusEnum.Billable;
timeActivity.BillableStatusSpecified = true;
timeActivity.Hours = 8;
timeActivity.Minutes = 0;
timeActivity.TxnDate = DateTime.Now.Date;
timeActivity.TxnDateSpecified = true;
//timeActivity.HourlyRate = new decimal(200);
//timeActivity.HourlyRateSpecified = true;
timeActivity.NameOf = TimeActivityTypeEnum.Employee;
timeActivity.NameOfSpecified = true;
timeActivity.CustomerRef = new ReferenceType()
{
name = resultCustomer.DisplayName,
Value = resultCustomer.Id
};
timeActivity.ItemRef = new ReferenceType()
{
name = resultEmployee.DisplayName,
Value = resultEmployee.Id,
};
timeActivity.Description = "Did something";
TimeActivity timeActivityResult = commonService.Add(timeActivity);
ItemRef is for providing service Items. Please use timeActivity.AnyIntuitObject for specifying vendor or employee
timeActivity.NameOf = TimeActivityTypeEnum.Employee;
timeActivity.NameOfSpecified = true;
timeActivity.ItemElementName = ItemChoiceType5.EmployeeRef;
timeActivity.AnyIntuitObject= new ReferenceType()
{
name = resultEmployee.DisplayName,
Value = resultEmployee.Id,
};

Prevent duplicate code while using linq

I am currently inserting / updating data in a SQL database using C# and linq. The following code works perfectly but i feel that it is messy and is duplicated.
Could you please have a look at the following code and tell me if there is a quicker to update data instead of me having to duplicate my code
Thank you
Incident inc = new Incident
{
AccountID = AccountID,
SiteID = siteID,
DepartmentID = departmentID,
LocationID = LocationID,
QuestionCategoryID = CategoryID,
IncidentSourceID = IncidentSourceID,
IncidentTypeID = IncidentTypeID,
NonConformanceTypeID = NonConID,
ProductGroupID = ProductGroupID,
ProductID = ProductID,
ComponentID = ComponentID,
ProductReference = prodRef,
CurrentAssignedUserID = UserId,
CurrentAssignedContactID = contactid,
OriginalAssignedUser = UserId,
OriginalAssignedContact = contactid,
LoggedByUserID = logUserId,
LoggedByContactID = logContactid,
IncidentTitleID = IncidentTitleID,
Title = IncidentTitle.ToString(),
Description = problemDesc,
Comments = comments,
ActionsRequired = actions,
RiskPriorityID = RiskPriorityTypeID,
AffectedPartyID = affectedPartyID,
ImpactLevel = Convert.ToInt32(impact),
Justification = justification,
EsculationDate = DateTime.Today,
PriorityID = PriorityID,
OriginalPriorityID = PriorityID,
CreatedByUser = Convert.ToInt32(loggedInUserID),
UpdatedBy = Convert.ToString(loggedInUserID),
RiskID = RiskID,
Active = true,
StatusID = 1,
DelayedDate = null,
IncidentCloseDate = null,
IncidentDate = DateTime.Now,
IncidentPendingDate = DateTime.Now,
LoggedDate = DateTime.Now,
LastUpdated = DateTime.Now,
LastActionTaken = DateTime.Now
};
// Save the data to the database
if (Request.QueryString["IncidentID"] == null)
{
// Insert a new incident.
db.Incidents.Add(inc);
db.SaveChanges();
}
else
{
//update an existing incident.
long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
var record = db.Incidents.Where(i => i.IncidentID == ID).FirstOrDefault();
record.AccountID = AccountID;
record.SiteID = siteID;
record.DepartmentID = departmentID;
record.LocationID = LocationID;
record.QuestionCategoryID = CategoryID;
record.IncidentSourceID = IncidentSourceID;
record.IncidentTypeID = IncidentTypeID;
record.NonConformanceTypeID = NonConID;
record.ProductGroupID = ProductGroupID;
record.ProductID = ProductID;
record.ComponentID = ComponentID;
record.ProductReference = prodRef;
record.CurrentAssignedUserID = UserId;
record.CurrentAssignedContactID = contactid;
record.OriginalAssignedUser = UserId;
record.OriginalAssignedContact = contactid;
record.LoggedByUserID = logUserId;
record.LoggedByContactID = logContactid;
record.IncidentTitleID = IncidentTitleID;
record.Title = IncidentTitle.ToString();
record.Description = problemDesc;
record.Comments = comments;
record.ActionsRequired = actions;
record.RiskPriorityID = RiskPriorityTypeID;
record.AffectedPartyID = affectedPartyID;
record.ImpactLevel = Convert.ToInt32(impact);
record.Justification = justification;
record.EsculationDate = DateTime.Today;
record.PriorityID = PriorityID;
record.OriginalPriorityID = PriorityID;
record.CreatedByUser = Convert.ToInt32(loggedInUserID);
record.UpdatedBy = Convert.ToString(loggedInUserID);
record.RiskID = RiskID;
record.Active = true;
record.StatusID = 1;
record.DelayedDate = null;
record.IncidentCloseDate = null;
record.IncidentDate = DateTime.Now;
record.IncidentPendingDate = DateTime.Now;
record.LoggedDate = DateTime.Now;
record.LastUpdated = DateTime.Now;
record.LastActionTaken = DateTime.Now;
db.SaveChanges();
}
Just set your properties the once, regardless of weather its an existing entity or not.
var id = Request.QueryString["IncidentID"];
var incidentId = String.IsNullOrEmpty(id) ? 0 : int.Parse(id);
var record = incidentId !=0 ?
db.Incidents.FirstOrDefault(i => i.IncidentID == incidentId); : new Incident();
record.AccountID = AccountID;
record.SiteID = siteID;
record.DepartmentID = departmentID;
//etc.......
if (incidentId == 0)
{
//set any fields here that are for add only
record.CreatedByUser = ...
db.Incidents.Add(record);
}
db.SaveChanges();
Incident inc;
if (Request.QueryString["IncidentID"] == null)
{
inc = new Incident();
// set properties that are specific to insert
db.Incidents.Add(inc);
}
else
{
long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
inc = db.Incidents.Where(i => i.IncidentID == ID).First();
// set properties that are specific to update
}
// set common properties
db.SaveChanges();
You could do the following:
var incidentInitializer = new Action<Incident>(incident =>
{
incident.AccountID = AccountID,
incident.SiteID = siteID,
...
};
// Save the data to the database
if (Request.QueryString["IncidentID"] == null)
{
// Insert a new incident.
var inc = new Incident();
incidentInitializer(inc);
db.Incidents.Add(inc);
db.SaveChanges();
}
else
{
//update an existing incident.
long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
var record = db.Incidents.Where(i => i.IncidentID == ID).FirstOrDefault();
incidentInitializer(record);
db.SaveChanges();
}

Categories

Resources