QBO IPP API - how to link a payment to an invoice - c#

I am able to successfully create an invoice, and a payment, but don't seem to be able to properly link the payment to the invoice. I have tried several variations, but it either does not link at all, or I get a "Business Validation Error: Unexpected Internal Error." error in my error logs. Below is my c# code. Is there a simplified way (example) of linking a payment to an invoice?
Invoice i = QBGet_InvoiceByMDVInvoiceNum(MDVInvoiceNum);
Payment p = new Payment();
Customer customer = QBGet_CustomerByName(ClientName, "CompanyName");
Account acc = QBGet_AccountsReceivableAccount();
p.TxnDate = DateTime.Now;
p.TxnDateSpecified = true;
List<Line> lineList1 = new List<Line>();
Line pmtLine = new Line();
pmtLine.Amount = ReceivedPaymentAmt;
pmtLine.AmountSpecified = true;
List<LinkedTxn> linkedTxnList = new List<LinkedTxn>();
LinkedTxn linkedtxn = new LinkedTxn();
linkedtxn.TxnId = i.Id;
linkedtxn.TxnType = "invoice";
linkedTxnList.Add(linkedtxn);
pmtLine.LinkedTxn = linkedTxnList.ToArray();
//p.LinkedTxn = linkedTxnList.ToArray();
lineList1.Add(pmtLine);
p.Line = lineList1.ToArray();
p.CustomerRef = new ReferenceType()
{
Value = customer.Id
};
p.DepositToAccountRef = new ReferenceType() { Value = acc.Id };
p.PaymentRefNum = ReceiptCheckNo;
p.TotalAmt = ReceivedPaymentAmt;
p.TotalAmtSpecified = true;
DataService service = new DataService(context);
var result = service.Add<Payment>(p);
I have also tried this approach:
p.CustomerRef = new ReferenceType()
{
Value = customer.Id
};
p.PrivateNote ="ReferralID: " + ReferralId + "\r\n" + "PaymentDetailID: " + PaymentDetailID + "\r\n" + Comments;
p.PaymentRefNum = ReceiptCheckNo;
p.PaymentType = PaymentTypeEnum.Check;
p.PaymentTypeSpecified = true;
p.DocNumber = MDVInvoiceNum;
p.TotalAmt = ReceivedPaymentAmt;
p.TotalAmtSpecified = true;
p.TxnDate = PaymentReceivedDate;
p.TxnDateSpecified = true;
LinkedTxn[] lt = {new LinkedTxn()
{
TxnId=i.Id,
TxnType="invoice"
}
};
Line l = new Line()
{
Amount = ReceivedPaymentAmt,
LinkedTxn = lt
};
Line[] aryL = {l};
DataService service = new DataService(context);
Payment pmt = service.Add(p);
p.Line = aryL;
p.LinkedTxn = lt;
Payment pmt2 = service.Update(p);

Sharing the Java code and corresponding working JSON payload. It might help.
private void paymentAgainstInvoice() {
Payment payment = new Payment();
Date currentDateTime = null;
try {
currentDateTime = DateUtils.getCurrentDateTime();
} catch (ParseException e) {
e.printStackTrace();
}
payment.setTxnDate(currentDateTime);
Line line = new Line();
line.setAmount(new BigDecimal("100"));
LinkedTxn linkedTxn = new LinkedTxn();
linkedTxn.setTxnId("248");
linkedTxn.setTxnType("Invoice");
List<LinkedTxn> linkedTxnList = new ArrayList<LinkedTxn>();
linkedTxnList.add(linkedTxn);
line.setLinkedTxn(linkedTxnList);
List<Line> lineList = new ArrayList<Line>();
lineList.add(line);
payment.setLine(lineList);
ReferenceType custReferenceType = new ReferenceType();
custReferenceType.setValue("29");
custReferenceType.setName("ABC");
payment.setCustomerRef(custReferenceType);
payment.setTotalAmt(new BigDecimal("100"));
ReferenceType accountRefType = new ReferenceType();
accountRefType.setValue("63");
payment.setPaymentRefNum("ABC-100-Invoice");
payment.setDepositToAccountRef(accountRefType );
try {
this.service.add(payment);
} catch (FMSException e) {
e.printStackTrace();
}
}
JSON payload ( Payment )
{
"CustomerRef":{
"value":"29",
"name":"ABC"
},
"DepositToAccountRef":{
"value":"63"
},
"PaymentRefNum":"ABC-100-Invoice",
"TotalAmt":100,
"TxnDate":"2014-11-30",
"Line":[
{
"Amount":100,
"LinkedTxn":[
{
"TxnId":"248",
"TxnType":"Invoice"
}
]
}
]
}

Related

PayPal API Validation Error: Item amount must add up to specified amount subtotal (or total if amount details not specified)

I'm currently having an error(as mentioned in the title). I don't know what's wrong or which line I'm having problems with. I'm sure all the values mentioned in the error are the same but it still pops up the same error.
My aim is to make the all the values the same to solve the error.
Here's the full description of my error:
{
"name": "https://stackoverflow.com/VALIDATION_ERROR",
"details": [
{
"field": "transactions[0]",
"issue": "Item amount must add up to specified amount subtotal (or total if amount details not specified)"
}
],
"message": "Invalid request - see details",
"information_link": "https://developer.paypal.com/docs/api/payments/#errors",
"debug_id": "67a354f1a8fc7"
}
Please help!
Here are my codes for reference:
// scList has 2 values inside.
List<UserShoppingCartDAO> scList = UserShoppingCartDAO.GetCartOfUser(uID);
List<Item> itms = new List<Item>();
ItemList itemList = new ItemList();
decimal deliveryCharges = 0;
string deliveryChargesStr = "";
decimal postagePackingCost = 0;
decimal examPaperPrice = 0;
int quantityOfExamPapers = 0;
decimal subtotal = 0;
decimal total = 0;
var transactionDetails = new Details();
var transactionAmount = new Amount();
Transaction tran = new Transaction();
for (int iCounter = 0; iCounter < scList.Count; iCounter++)
{
Product p = Product.getProduct(scList[iCounter].ProductID.ToString());
deliveryCharges = p.price * 0.05m;
deliveryChargesStr = deliveryCharges.ToString();
postagePackingCost = 10m;
examPaperPrice = p.price;
quantityOfExamPapers = scList[iCounter].ProductQuantity;
subtotal = (quantityOfExamPapers * examPaperPrice);
total = subtotal + postagePackingCost;
var examPaperItem = new Item();
examPaperItem.name = p.productName;
examPaperItem.currency = "SGD";
examPaperItem.price = total.ToString();
examPaperItem.sku = p.productID.ToString();
examPaperItem.description = p.productDesc;
examPaperItem.quantity = quantityOfExamPapers.ToString();
itms.Add(examPaperItem);
itemList.items = itms;
// var transactionDetails = new Detail
transactionDetails.tax = "0";
if (transactionDetails.shipping == null)
{
transactionDetails.shipping = postagePackingCost.ToString();
}
else
{
decimal total2 = decimal.Parse(transactionDetails.shipping) + postagePackingCost;
transactionDetails.shipping = total2.ToString();
}
if (transactionDetails.subtotal == null)
{
transactionDetails.subtotal = subtotal.ToString();
}
else
{
decimal total2 = decimal.Parse(transactionDetails.subtotal) + subtotal;
transactionDetails.subtotal = total2.ToString();
}
//transactionDetails.shipping = postagePackingCost.ToString();
//transactionDetails.subtotal = subtotal.ToString("0.00");
// var transactionAmount = new Amount();
transactionAmount.currency = "SGD";
if (transactionAmount.total == null)
{
transactionAmount.total = total.ToString();
}
else
{
decimal total2 = decimal.Parse(transactionAmount.total) + total;
transactionAmount.total = total2.ToString();
}
transactionAmount.details = transactionDetails;
// Transaction tran = new Transaction();
tran.description = scList[0].ProductDescription;
tran.invoice_number = Guid.NewGuid().ToString();
tran.amount = transactionAmount;
// transaction.item_list = new List<Item>();
tran.item_list = itemList;
transactionList.Add(tran);
}
transactionList.Remove(transactionList[1]);
//Authenticate with paypal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
//Get APIContent Object
var apiContext = new APIContext(accessToken);
var payer = new Payer();
payer.payment_method = "paypal";
var redirectUrls = new RedirectUrls();
redirectUrls.cancel_url = "http://localhost60681/Cancel.aspx";
redirectUrls.return_url = "http://localhost:60681/CompletePurchase.aspx";
var payment = Payment.Create(apiContext, new Payment
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirectUrls
});
Session["paymentId"] = payment.id;
foreach (var link in payment.links)
{
if (link.rel.ToLower().Trim().Equals("approval_url"))
{
Response.Redirect(link.href);
}
}

Issu in Adwords API, Failed to refresh access token - "error" : "invalid_grant"

I am writing a code to get the search volume using adwords api in c# but it gives me the error on line "page = targetingIdeaService.get(selector);", below is my code, I found this code example online.
AdWordsAppConfig config = new AdWordsAppConfig();
config.OAuth2ClientId = "MY_OAUTH2ClientID Here";
config.OAuth2ClientSecret = "MY_OAUTH2ClientSecret Here";
AdWordsUser user = new AdWordsUser(config);
AdWordsUser user1=new AdWordsUser()
using (TargetingIdeaService targetingIdeaService = (TargetingIdeaService)user.GetService(AdWordsService.v201710.TargetingIdeaService))
{
TargetingIdeaSelector selector = new TargetingIdeaSelector();
selector.requestType = RequestType.STATS;
selector.ideaType = IdeaType.KEYWORD;
selector.requestedAttributeTypes = new AttributeType[] {
AttributeType.KEYWORD_TEXT,
AttributeType.SEARCH_VOLUME,
AttributeType.AVERAGE_CPC,
AttributeType.COMPETITION,
AttributeType.TARGETED_MONTHLY_SEARCHES
};
List<SearchParameter> searchParameters = new List<SearchParameter>();
RelatedToQuerySearchParameter relatedToQuerySearchParameter =
new RelatedToQuerySearchParameter();
relatedToQuerySearchParameter.queries = new String[] { keyword };
searchParameters.Add(relatedToQuerySearchParameter);
LanguageSearchParameter languageParameter = new LanguageSearchParameter();
Language english = new Language();
english.id = 1000;
languageParameter.languages = new Language[] { english };
searchParameters.Add(languageParameter);
NetworkSetting networkSetting = new NetworkSetting();
networkSetting.targetContentNetwork = false;
networkSetting.targetGoogleSearch = true;
networkSetting.targetPartnerSearchNetwork = false;
networkSetting.targetSearchNetwork = false;
NetworkSearchParameter networkSearchParameter = new NetworkSearchParameter() { networkSetting = networkSetting };
searchParameters.Add(networkSearchParameter);
selector.searchParameters = searchParameters.ToArray();
Paging paging = Paging.Default;
selector.paging = paging;
TargetingIdeaPage page = new TargetingIdeaPage();
try
{
do
{
page = targetingIdeaService.get(selector); // gives error on this line
if (page.entries != null && page.entries.Length > 0)
{
foreach (TargetingIdea targetingIdea in page.entries)
{
Dictionary<AttributeType, Google.Api.Ads.AdWords.v201710.Attribute> ideas =
targetingIdea.data.ToDict();
long averageMonthlySearches = (ideas[AttributeType.SEARCH_VOLUME] as LongAttribute).value;
string keywordRes = (ideas[AttributeType.KEYWORD_TEXT] as StringAttribute).value;
Money averageCpc = (ideas[AttributeType.AVERAGE_CPC] as MoneyAttribute).value;
double competition = (ideas[AttributeType.COMPETITION] as DoubleAttribute).value;
}
}
selector.paging.IncreaseOffset();
} while (selector.paging.startIndex < page.totalNumEntries);
Console.WriteLine("Number of related keywords found: {0}", page.totalNumEntries);
}
catch (AdWordsException e)
{
throw new System.ApplicationException("Failed to retrieve related keywords.", e);
}
}
Please help what is wrong with my code or how I can achieve the functionality.
Thanks & Regards,

Viewing XML output from C#

I'm trying to work with the UPS api to create a shipping label. The UPS api uses a webservice to send an XML request to UPS. UPS then sends a response back. Here is my question.
Is there a way to view the XML that is outputted when I call the "shipmentRequest" method?
This is the first time I've used an API and a webservice so if you need me to provide more information just let me know.
Thanks!
EDIT: Here is my C# code
ShipService shpSvc = new ShipService();
ShipmentRequest shipmentRequest = new ShipmentRequest();
UPSSecurity upss = new UPSSecurity();
//shpSvc.Url = "https://onlinetools.ups.com/webservices/Ship";
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = apiCode;
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = userName;
upssUsrNameToken.Password = password;
upss.UsernameToken = upssUsrNameToken;
shpSvc.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "nonvalidate" };
request.RequestOption = requestOption;
shipmentRequest.Request = request;
ShipmentType shipment = new ShipmentType();
shipment.Description = "Ship webservice example";
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = accountNumber;
PaymentInfoType paymentInfo = new PaymentInfoType();
ShipmentChargeType shpmentCharge = new ShipmentChargeType();
BillShipperType billShipper = new BillShipperType();
billShipper.AccountNumber = accountNumber;
shpmentCharge.BillShipper = billShipper;
shpmentCharge.Type = "01";
ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
paymentInfo.ShipmentCharge = shpmentChargeArray;
shipment.PaymentInformation = paymentInfo;
ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] addressLine = { "480 Parkton Plaza" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "Timonium";
shipperAddress.PostalCode = "21093";
shipperAddress.StateProvinceCode = "MD";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipper.Name = "ABC Associates";
shipper.AttentionName = "ABC Associates";
ShipPhoneType shipperPhone = new ShipPhoneType();
shipperPhone.Number = "1234567890";
shipper.Phone = shipperPhone;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] shipFromAddressLine = { "Ship From Street" };
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "Timonium";
shipFromAddress.PostalCode = "21093";
shipFromAddress.StateProvinceCode = "MD";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipFrom.AttentionName = "Mr.ABC";
shipFrom.Name = "ABC Associates";
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { "Some Street" };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = "Roswell";
shipToAddress.PostalCode = "30076";
shipToAddress.StateProvinceCode = "GA";
shipToAddress.CountryCode = "US";
shipTo.Address = shipToAddress;
shipTo.AttentionName = "DEF";
shipTo.Name = "DEF Associates";
ShipPhoneType shipToPhone = new ShipPhoneType();
shipToPhone.Number = "1234567890";
shipTo.Phone = shipToPhone;
shipment.ShipTo = shipTo;
ServiceType service = new ServiceType();
service.Code = "01";
shipment.Service = service;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "1";
ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
uom.Code = "LBS";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
PackagingType packType = new PackagingType();
packType.Code = "02";
package.Packaging = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
LabelSpecificationType labelSpec = new LabelSpecificationType();
LabelStockSizeType labelStockSize = new LabelStockSizeType();
labelStockSize.Height = "6";
labelStockSize.Width = "4";
labelSpec.LabelStockSize = labelStockSize;
LabelImageFormatType labelImageFormat = new LabelImageFormatType();
labelImageFormat.Code = "SPL";
labelSpec.LabelImageFormat = labelImageFormat;
shipmentRequest.LabelSpecification = labelSpec;
shipmentRequest.Shipment = shipment;
ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
MessageBox.Show("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
MessageBox.Show("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
You can inherit from the UPS service and read the response as xml by providing your own XmlWriter by overriding GetWriterForMessage(). You can see a working example here.
i am using this code display xml it may help you.
XDocument mySourceDoc = new XDocument();
mySourceDoc = XDocument.Load(shipmentResponse);
txtxml.Text = mySourceDoc.ToString();

Expedia hotel API

I am working on Expedia hotel API.All the function are working except booking.All the other request using GET method for requesting.But in booking we have to use the POST method with different URL.So i changed the URL for request but still getting the error.
My codes are
HotelServicesImplService client = new HotelServicesImplService();
HotelRoomReservationRequest bookreq = new HotelRoomReservationRequest();
HotelRoomReservationResponse bookres = new HotelRoomReservationResponse();
addressInfo bookad = new addressInfo();
reservationInfo bookinfo = new reservationInfo();
client.Url = "https://book.api.ean.com/ean-services/rs/hotel/v3";
//bookreq.minorRevSpecified = true;
//bookreq.minorRev = 25;
bookreq.hotelId = 106347;
bookreq.apiKey = "api";
bookreq.cid = "cid";
bookreq.arrivalDate = "12/11/2013";
bookreq.departureDate = "12/13/2013";
bookreq.supplierType = SupplierType.E;
bookreq.rateKey = "af00b688-acf4-409e-8bdc-fcfc3d1cb80c";
bookreq.roomTypeCode = "198058";
bookreq.rateCode = "484072";
bookreq.RoomGroup = new[] { new Room
{
numberOfAdults=Convert.ToInt32(2),
numberOfChildren=Convert.ToInt32(0),
childAges=new int[] {} ,
firstName="Test Booking",
lastName="Test Booking",
bedTypeId="23",
smokingPreference=SmokingPreference.NS,
}};
float i = float.Parse("231.18");
bookreq.currencyCode = "USD";
bookreq.chargeableRate = i;
bookinfo.email = "ranaabhi007#yahoo.com";
bookinfo.firstName = "TestBooking";
bookinfo.lastName = "TestBooking";
bookinfo.homePhone = "2145370159";
bookinfo.workPhone = "2145370159";
bookinfo.creditCardType = "CA";
bookinfo.creditCardNumber = "5401999999999999";
bookinfo.creditCardIdentifier = "TestBooking";
bookinfo.creditCardExpirationMonth = "12";
bookinfo.creditCardExpirationYear = "2015";
bookad.city = "Seattle";
bookad.stateProvinceCode = "WA";
bookad.countryCode = "US";
bookad.postalCode = "98004";
bookreq.ReservationInfo = bookinfo;
bookad.address1 = "travelnow";
//bookad.city = txtCity.Text;
//bookad.stateProvinceCode = txtState.Text;
//bookad.countryCode = txtCountry.Text;
//bookad.postalCode = txtPostal.Text;
bookreq.AddressInfo = bookad;
bookres = client.getReservation(bookreq);
// HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(client);
Response.Write(bookres.confirmationNumbers);
Response.Write(bookres.departureDate);
Response.Write(bookres.drivingDirections);
Response.Write(bookres.CouponInformationResponse);
but i am still getting the error
The request failed with HTTP status 404: Not Found.
Are you sure your URL is correct? According to the documentation, it should be
https://book.api.ean.com/ean-services/rs/hotel/v3/res

Can't save invoice on qb online correctly

I am able to create invoice on quickbook online, but when i check quickbook invoice online, it create the item lists but the price and description is missing. What i am doing wrong.
invoice.AlternateId = new NameValue[] { new NameValue() { Name = "InvoiceID", Value = service.InvoiceId } };
InvoiceHeader Header = new InvoiceHeader();
Header.DocNumber = service.InvoiceId;
Header.TxnDate = service.ServiceDate;
Header.TxnDateSpecified = true;
Header.Msg = service.Note.ToString();
Header.Note = service.Note.ToString();
Header.CustomerId = new IdType() { idDomain = idDomainEnum.QBO, Value = service.CustomerNumberOnline };
Header.Currency = currencyCode.USD;
Header.ShipDate = service.ServiceDate;
Header.ShipDateSpecified = true;
//Print and Email Option fields
if (EmailPrintOption == "Both")
{
Header.ToBeEmailed = true;
Header.ToBeEmailedSpecified = true;
Header.ToBePrinted = true;
Header.ToBePrintedSpecified = true;
}
else if (EmailPrintOption == "print")
{
Header.ToBePrinted = true;
Header.ToBePrintedSpecified = true;
}
else if (EmailPrintOption == "email")
{
Header.ToBeEmailed = true;
Header.ToBeEmailedSpecified = true;
}
else
{
Header.ToBeEmailed = false;
Header.ToBeEmailedSpecified = false;
Header.ToBePrinted = false;
Header.ToBePrintedSpecified = false;
}
PhysicalAddress BillAddress = new PhysicalAddress();
BillAddress.Line1 = service.SoldToAddress;
BillAddress.City = service.SoldToCity;
BillAddress.CountrySubDivisionCode = service.SoldToState;
BillAddress.PostalCode = service.SoldToZip;
BillAddress.Tag = new string[] { "Billing" };
Header.BillAddr = BillAddress;
PhysicalAddress ShipAddress = new PhysicalAddress();
ShipAddress.Line1 = service.JobJocationAddress;
ShipAddress.City = service.JobLocationCity;
ShipAddress.CountrySubDivisionCode = service.JobLocationState;
ShipAddress.PostalCode = service.JobLocationZip;
BillAddress.Tag = new string[] { "Shipping" };
Header.ShipAddr = ShipAddress;
decimal discount;
if (decimal.TryParse(service.Discount, out discount))
{
Header.ItemElementName = ItemChoiceType2.DiscountAmt;
Header.Item = -1 * discount; //discount must be negative
}
InvoiceLine[] InvoiceLines = new InvoiceLine[TaskOnlineIDs.Count];
object[] intuitItems = new object[TaskOnlineIDs.Count];
for (int i = 0; i < InvoiceLines.Length; i++)
{
InvoiceLines[i] = new InvoiceLine();
InvoiceLines[i].ItemsElementName = new Intuit.Ipp.Data.Qbo.ItemsChoiceType2[]
{
Intuit.Ipp.Data.Qbo.ItemsChoiceType2.ItemId
};
InvoiceLines[i].Items = new object[] {
new IdType(){idDomain=idDomainEnum.QBO, Value=TaskOnlineIDs[i]}
};
}
invoice.Line = InvoiceLines;
Header.SalesTermName = service.PaymentType;
Header.SalesRepName = service.TechName;
Header.PONumber = service.PurchaseOrder;
invoice.Header = Header;
What i miss here ??
Here what happen is, when i add invoice lines to invoice it set amount of each item to "0" by default, so when i try to add discount pragmatically it give's me error of discount greater than subtotal which is correct. But my question is why do i need to add cost for each item explicitly when i have already defined them earlier. We should add only itemId and rest QB should calculate.

Categories