I am trying to submit a Credit Card Payment using the QuickBooks Online SDK, but when I run my code I get the following error:
Raw Credit Card Number not supported. Tokenized Credit Card Number
Required
Here is what I have. Can anyone explain how I can tokenize the card number using sdk before using it in this manner?
public Payment PaymentCreditCard(Order order, ServiceContext qboContextoAuth)
{
Payment payment = new Payment();
payment.TxnDate = Convert.ToDateTime(order.DateCreated);
payment.TxnDateSpecified = true;
Account depositAccount = Helper.FindOrAddAccount(qboContextoAuth, AccountTypeEnum.Bank, AccountClassificationEnum.Asset);
payment.DepositToAccountRef = new ReferenceType()
{
name = depositAccount.Name,
Value = depositAccount.Id
};
PaymentMethod paymentMethod = Helper.FindOrAdd<PaymentMethod>(qboContextoAuth, new PaymentMethod());
payment.PaymentMethodRef = new ReferenceType()
{
name = paymentMethod.Name,
Value = paymentMethod.Id
};
Customer customer = Helper.FindOrAdd<Customer>(qboContextoAuth, new Customer());
payment.CustomerRef = new ReferenceType()
{
name = customer.DisplayName,
Value = customer.Id
};
payment.PaymentType = PaymentTypeEnum.CreditCard;
CreditCardPayment creditCardPayment = new CreditCardPayment();
CreditChargeInfo creditChargeInfo = new CreditChargeInfo();
creditChargeInfo.BillAddrStreet = order.BillingAddress;
creditChargeInfo.CcExpiryMonth = Convert.ToInt32(order.CCExpMonth);
creditChargeInfo.CcExpiryMonthSpecified = true;
creditChargeInfo.CcExpiryYear = Convert.ToInt32(order.CCExpYear);
creditChargeInfo.CcExpiryYearSpecified = true;
creditChargeInfo.CCTxnMode = CCTxnModeEnum.CardNotPresent;
creditChargeInfo.CCTxnModeSpecified = true;
creditChargeInfo.CCTxnType = CCTxnTypeEnum.Charge;
creditChargeInfo.CCTxnTypeSpecified = true;
//reditChargeInfo.CommercialCardCode = "Cardcode" + Helper.GetGuid().Substring(0, 5);
creditChargeInfo.NameOnAcct = order.BillingName;
creditChargeInfo.Number = order.CCNum;
creditChargeInfo.PostalCode = order.BillingZip;
creditCardPayment.CreditChargeInfo = creditChargeInfo;
payment.AnyIntuitObject = creditCardPayment;
payment.TotalAmt = Convert.ToDecimal(order.TotalAmount);
payment.TotalAmtSpecified = true;
payment.UnappliedAmt = Convert.ToDecimal(order.TotalAmount);
payment.UnappliedAmtSpecified = true;
//Adding the Payment
Payment added = Helper.Add<Payment>(qboContextoAuth, payment);
return added;
}
From what I have gathered from the raw API, here is what I need:
https://developer.intuit.com/app/developer/qbpayments/docs/api/resources/all-entities/tokens
But I don't seem to be able to find such functionality in the SDK. Does anyone have experience doing this?
Here is the solution to this problem as of today (03/14/19):
public string getCardToken()
{
string cardToken="";
JObject jsonDecodedResponse;
string cardTokenJson = "";
string cardTokenEndpoint = "quickbooks/v4/payments/tokens";
string uri= paymentsBaseUrl + cardTokenEndpoint;
string cardTokenRequestBody = "{\"card\":{\"expYear\":\"2020\",\"expMonth\":\"02\",\"address\":{\"region\":\"CA\",\"postalCode\":\"94086\",\"streetAddress\":\"1130 Kifer Rd\",\"country\":\"US\",\"city\":\"Sunnyvale\"},\"name\":\"emulate=0\",\"cvc\":\"123\",\"number\":\"4111111111111111\"}}";
// send the request (token api call does not requires Authorization header, rest all payments call do)
HttpWebRequest cardTokenRequest = (HttpWebRequest)WebRequest.Create(uri);
cardTokenRequest.Method = "POST";
cardTokenRequest.ContentType = "application/json";
cardTokenRequest.Headers.Add("Request-Id", Guid.NewGuid().ToString());//assign guid
byte[] _byteVersion = Encoding.ASCII.GetBytes(cardTokenRequestBody);
cardTokenRequest.ContentLength = _byteVersion.Length;
Stream stream = cardTokenRequest.GetRequestStream();
stream.Write(_byteVersion, 0, _byteVersion.Length);
stream.Close();
// get the response
HttpWebResponse cardTokenResponse = (HttpWebResponse)cardTokenRequest.GetResponse();
using (Stream data = cardTokenResponse.GetResponseStream())
{
cardTokenJson= new StreamReader(data).ReadToEnd();
jsonDecodedResponse = JObject.Parse(cardTokenJson);
if (!string.IsNullOrEmpty(jsonDecodedResponse.TryGetString("value")))
{
cardToken = jsonDecodedResponse["value"].ToString();
}
}
return cardToken;
}
They may add an SDK option to do the same some day, but it's not available as of today!
Related
I want to integrate Stripe into my ASP.NET MVC application.
So, As the first step, I'm trying to do it with simple code.
This is my simple code below,
var customers = new CustomerService();
var charges = new ChargeService();
var publishableKey = "pk_test_51KseuBH1Mw1tyjglBiJls20038FcgbHr";
StripeConfiguration.SetApiKey(publishableKey);
StripeConfiguration.ApiKey = "sk_test_51KseuRqoYQ6YGD7TNzPp0051boOPvQ";
var customer = customers.Create(new CustomerCreateOptions
{
Email = "isanka.ad#gmail.com",
Source = publishableKey
});
var charge = charges.Create(new ChargeCreateOptions
{
Amount = 500,
Description = "Sample Charge",
Currency = "usd",
Customer = customer.Id
});
I have tried different codes on forams. But it always returns the same error below,
No such token: 'pk_test_51KseuBHaMw1tyjglBiJls20038FcgbHr'
This is my Stripe keys,
Did I define secret key and publishable key incorrectly?
The publishable key must not be used in your backend code. It is for your client-side code, as described in the documentation: https://stripe.com/docs/keys. Moreover, the Source property on the customer describes the payment method: https://stripe.com/docs/api/customers/create?lang=dotnet. I can recommend getting started with Stripe with the quick start guide: https://stripe.com/docs/payments/quickstart.
It seems you copied only the first line of the API Key.
Please make sure that you are using the complete API Key in your application, and you don't need to use publishable key in your backend integration.
The source value only accepts payment source created via the Token or Sources APIs.
When creating a customer in your sample code, the Source was assigned with publishableKey which is invalid and that's probably why "No such token" was returned.
If you do not have any source created upfront, then Source should be removed from your customer creation request.
I was missing creating the card and token
generate. Above I have assigned the publishable token as the source value, not generated token.
Here is the full working code.
public async Task<ProcessPaymentResult> ProcessPaymentAsync(ProcessPaymentRequest processPaymentRequest)
{
var processPaymentResult = new ProcessPaymentResult();
try
{
var customers = new CustomerService();
var charges = new ChargeService();
var options = new RequestOptions
{
ApiKey = // your Secret Key
};
#region Card payment checkout
var creditCardType = processPaymentRequest.CreditCardType.ToString();
var optionToken = new TokenCreateOptions
{
Card = new TokenCardOptions
{
Number = processPaymentRequest.CreditCardNumber,
ExpMonth = processPaymentRequest.CreditCardExpireMonth,
ExpYear = processPaymentRequest.CreditCardExpireYear,
Cvc = processPaymentRequest.CreditCardCvv2,
Name = processPaymentRequest.CreditCardName,
Currency = _workContext.WorkingCurrency.CurrencyCode
},
};
var tokenService = new TokenService();
Token paymentToken = await tokenService.CreateAsync(optionToken, options);
#endregion
#region Stripe Customer
var customer = new Customer();
var customerEmail = processPaymentRequest.CustomValues["CustomerEmail"].ToString();
// Search customer in Stripe
var stripeCustomer = await customers.ListAsync(new CustomerListOptions
{
Email = customerEmail,
Limit = 1
}, options);
if (stripeCustomer.Data.Count==0)
{
// create new customer
customer = await customers.CreateAsync(new CustomerCreateOptions
{
Source = paymentToken.Id,
Phone = processPaymentRequest.CustomValues["Phone"].ToString(),
Name = processPaymentRequest.CustomValues["CustomerName"].ToString(),
Email = customerEmail,
Description = $" { processPaymentRequest.CustomValues["RegisteredEmail"]};{ processPaymentRequest.CustomValues["CustomerName"] }",
}, options);
}
else
{
// use existing customer
customer = stripeCustomer.FirstOrDefault();
}
#endregion
#region Stripe charges
var charge = await charges.CreateAsync(new ChargeCreateOptions
{
Source = paymentToken.Id,//Customer = customer.Id,
Amount = (int)(Math.Round(processPaymentRequest.OrderTotal, 2) * 100),
Currency = _workContext.WorkingCurrency.CurrencyCode,
ReceiptEmail = customer.Email,
Description = $" { processPaymentRequest.CustomValues["RegisteredEmail"]};{ processPaymentRequest.CustomValues["CustomerName"] }",
}, options);
if (charge.Status.ToLower().Equals("succeeded"))
{
processPaymentResult.NewPaymentStatus = PaymentStatus.Paid;
processPaymentResult.CaptureTransactionId = charge.Id;
}
else
{
processPaymentResult.AddError("Error processing payment." + charge.FailureMessage);
}
#endregion
}
catch (Exception ex)
{
processPaymentResult.AddError(ex.Message);
}
return processPaymentResult;
}
You need to add secretKey in the setapikey function.
// StripeConfiguration.SetApiKey(publishableKey);
StripeConfiguration.SetApiKey(secretKey);
I'm developing a C# Winapp for connecting Magento to create customer data using SOAP API V2 and encountered an error like this when my program is trying to send a customer data to the Magento server.
It works fine if I send it with http but it won't work with https and I need to use https. How to make it work?
Here's my code for sending data:
PortTypeClient mservice = new PortTypeClient();
var mlogin = mservice.login("User", "apikey");
int newCustomerCreateID = 0;
filters myfilter = new filters();
// Create Customer
customerCustomerEntityToCreate customerCreate = new customerCustomerEntityToCreate();
//fill attributes
customerCreate.email = SessionStore.getEmail();
customerCreate.telephone = Int32.Parse(SessionStore.getTel());
customerCreate.password = SessionStore.getTel();
customerCreate.firstname = SessionStore.getFName();
customerCreate.lastname = SessionStore.getLName();
customerCreate.middlename = "";
customerCreate.id_card = Int32.Parse(SessionStore.getIdCard());
customerCreate.store_id = 1;
customerCreate.store_idSpecified = true;
customerCreate.website_id = 1;
customerCreate.website_idSpecified = true;
customerCreate.group_id = 1;
customerCreate.group_idSpecified = true;
//customerCreate.suffix = "P";
customerCreate.prefix = SessionStore.getPrefix();
customerCreate.dob = SessionStore.getBdate();
//customerCreate.taxvat = "123456";
customerCreate.gender = Int32.Parse(SessionStore.getGenderNum()); //1-Male;2-Female
customerCreate.genderSpecified = true;
newCustomerCreateID = mservice.customerCustomerCreate(mlogin, customerCreate);
mservice.endSession(mlogin);
Am using DocuSign Api's for signing documents. Now I have created template in DocuSign and Uploaded the PDF's there.
Now when user click's on submit, we need to auto populate docusign pdf's and I don't have custom fields added at docusign and it should be dynamic. Below is the code which is not working.
public string SignDocument()
{
var accountId = Login();
var url = GetRecipientDocumentUrl(accountId);
return url;
}
private string Login()
{
string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
DocuSign.eSign.Client.Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
// we will retrieve this from the login() results
string accountId = null;
// the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
var authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
// find the default account for this user
foreach (LoginAccount loginAcct in loginInfo.LoginAccounts)
{
if (loginAcct.IsDefault == "true")
{
accountId = loginAcct.AccountId;
break;
}
}
if (accountId == null)
{ // if no default found set to first account
accountId = loginInfo.LoginAccounts[0].AccountId;
}
return accountId;
}
private string GetRecipientDocumentUrl(string accountId)
{
//var envelope = BuildEnvelopeDefinition(documents);
var envelope = BuildEnvelopeDefinition();
// |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
var envelopesApi = new EnvelopesApi();
//TemplateCustomFields
var summary = envelopesApi.CreateEnvelope(accountId, envelope);
//===========================================================
// Step 3: Create Embedded Signing View (URL)
//===========================================================
var viewOptions = BuildRecipientViewRequest(envelope);
var recipientView = envelopesApi.CreateRecipientView(accountId, summary.EnvelopeId, viewOptions);
return recipientView.Url;
}
private EnvelopeDefinition BuildEnvelopeDefinition()
{
TemplateRole templateRole = new TemplateRole();
templateRole.Email = "kpothireddy#firstam.com";
templateRole.Name = "Sample";
templateRole.RoleName = "1";
templateRole.Tabs = new Tabs();
templateRole.Tabs.TextTabs = new List<Text>();
Text textTab = new Text();
textTab.TabLabel = "Approved by";
textTab.Value = "Kranthi";
//textTab.XPosition = "100";
//textTab.YPosition = "100";
templateRole.Tabs.TextTabs.Add(textTab);
templateRole.ClientUserId = Guid.NewGuid().ToString();
List<TemplateRole> rolesList = new List<TemplateRole>();
rolesList.Add(templateRole);
//rolesList.Add(templateRole1);
var envelope = new EnvelopeDefinition
{
TemplateRoles = rolesList,
//TemplateId = "3b07a774-5ec5-4bbd-928a-a4b0bace2fc5",
TemplateId = "44d25c06-4fc3-4cbe-a9d0-7e0e1e3013bc", //Prefill
Status = "sent"
};
//Envelope e = new Envelope();
return envelope;
}
private RecipientViewRequest BuildRecipientViewRequest(EnvelopeDefinition envelope)
{
RecipientViewRequest viewOptions = new RecipientViewRequest()
{
ReturnUrl = ReturnUrl,
ClientUserId = envelope.TemplateRoles.First().ClientUserId, // must match clientUserId set in step #2!
AuthenticationMethod = "email",
UserName = envelope.TemplateRoles.First().Name,
Email = envelope.TemplateRoles.First().Email
//UserName = envelope.Recipients.Signers.First().Name,
//Email = envelope.Recipients.Signers.First().Email
};
return viewOptions;
}
Could you please help me out.
I trying using Google Analytics with C# to get stats information to display in my webiste
Here is my code
public ActionResult Index()
{
string userName = "admin#email.com";
string passWord = "mypass";
string profileId = "ga:xxxxxxxx";
string key = "2d751338cb092ef8da65f716e37a48604386c9sw";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data"+key;
var service = new AnalyticsService("API Project");
service.setUserCredentials(userName, passWord);
var dataQuery = new DataQuery(dataFeedUrl)
{
Ids = profileId,
Metrics = "ga:pageviews",
Sort = "ga:pageviews",
GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
};
var dataFeed = service.Query(dataQuery);
var totalEntry = dataFeed.Entries[0];
ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var yesterdayEntry = dataFeed.Entries[0];
ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var todayEntry = dataFeed.Entries[0];
ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;
return View(dataFeed.Entries);
}
But when i run the code it always said "{"Invalid credentials"}"
Not sure why i facing this error while i checked many time about the key,username,password and profileId
Anyone facing this problem,can help me?
Many thanks
I think that your url is wrong. try in this way (you are missing ?key=).
string dataFeedUrl = "https://www.google.com/analytics/feeds/data?key="+key;
refer this google example where there is this example that should help you
public DataFeedExample()
{
// Configure GA API.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TABLE_ID;
query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:visits,ga:bounces";
query.Segment = "gaid::-11";
query.Filters = "ga:medium==referral";
query.Sort = "-ga:visits";
query.NumberToRetrieve = 5;
query.GAStartDate = "2010-03-01";
query.GAEndDate = "2010-03-15";
Uri url = query.Uri;
Console.WriteLine("URL: " + url.ToString());
// Send our request to the Analytics API and wait for the results to
// come back.
feed = asv.Query(query);
}
refer also this guide to configure your project
Also follow this guide to use OAuth 2.0
I am using the PayPal sandbox in ASP.Net C# 4.0. I added the following web references:
https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
When I run this code:
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq req = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutRequestType()
{
Version = Version,
SetExpressCheckoutRequestDetails = reqDetails
}
};
// query PayPal and get token
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutResponseType resp = BuildPayPalSandboxWebservice().SetExpressCheckout(req);
In my resp object, the error message says:
Security header is not valid
I was told to give it correct API credentials. I signed up on developer.paypal.com and i'm assuming the email address and password i used are my valid credentials. How and where do I give it my API credentials? Thanks
Did you check the endpoint addresses in your web.config file
Those should be referenced to following url's
For API Certificate => SOAP https://api.sandbox.paypal.com/2.0/
For API Signature => SOAP https://api-3t.sandbox.paypal.com/2.0/
If you are using Signature then use the following code
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"], //Not paypal login username
Password = ConfigurationManager.AppSettings["PayPalPassword"], //not login password
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
To get Paypal signature follow the link
For more info click here
Update:
Please check the following code it is working for me
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"],
Password = ConfigurationManager.AppSettings["PayPalPassword"],
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
PaymentDetailsItemType[] pdItem = new PaymentDetailsItemType[1];
pdItem[0] = new PaymentDetailsItemType()
{
Amount = new BasicAmountType(){currencyID = CurrencyCodeType.USD,Value = ItemPrice},
Name = ItemName,
Number = ItemNumber,
Description = ItemDescription,
ItemURL = ItemUrl
};
SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
sdt.NoShipping = "1";
PaymentDetailsType pdt = new PaymentDetailsType()
{
OrderDescription = OrderDesc,
PaymentDetailsItem = pdItem,
OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = ItemPrice
}
};
sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
sdt.CancelURL = "http://localhost:62744/PaymentGateway/PaymentFailure.aspx";
sdt.ReturnURL = "http://localhost:62744/PaymentGateway/ExpressCheckoutSuccess.aspx";
SetExpressCheckoutReq req = new SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
{
SetExpressCheckoutRequestDetails = sdt,
Version = "92.0"
}
};
var paypalAAInt = new PayPalAPIAAInterfaceClient();
var resp = paypalAAInt.SetExpressCheckout(ref type, req);
if (resp.Errors != null && resp.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
resp.Errors[0].LongMessage);
}
Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
ConfigurationManager.AppSettings["PayPalOriginalUrl"], resp.Token));