Getting "Received unknown parameter: amounts" for bank Account "Verify" function for jaymedavis/stripe.net code.? - wcf

I am implementing WCF service to implement online Net banking using github jaymedavis/stripe.net code (https://github.com/jaymedavis/stripe.net#charges).
here is my code for creating customer, Bank Account and Bank Account service for verifying Bank account and Creating charges.
Code:
//1. Create Customer
var myCustomer = new StripeCustomerCreateOptions();
myCustomer.Email = "pork#email.com";
myCustomer.Description = "Johnny Tenderloin (pork#email.com)";
//myCustomer.SourceToken = *token*;
//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
//2. Create Customer Service
var customerService = new StripeCustomerService(StripeApiKey);
StripeCustomer stripeCustomer = customerService.Create(myCustomer);
//3. Create bankAccount
var myBankAccount = new BankAccountCreateOptions
{
SourceBankAccount = new SourceBankAccount()
{
AccountNumber = "000123456789", //,
Country = "US",
Currency = "usd",
AccountHolderName = "Frank", //"Johnny Tenderloin",
AccountHolderType = BankAccountHolderType.Individual,
RoutingNumber = "110000000", //"021000021",
Metadata = new Dictionary<string, string>
{
{ "Name", "Ray Barone" },
{ "OftenSays", "Thatttttt's right" }
}
}
};
//4. Create bankAccount Service
var bankAccountService = new BankAccountService(StripeApiKey);
CustomerBankAccount bankAccount = bankAccountService.Create(stripeCustomer.Id, myBankAccount);
BankAccountVerifyOptions bankAccountVerifyOpt = new BankAccountVerifyOptions();
bankAccountVerifyOpt.AmountOne = 32;
bankAccountVerifyOpt.AmountTwo = 45;
//
//5. Verify bankAccount or service
bankAccount = bankAccountService.Verify(stripeCustomer.Id, bankAccount.Id, bankAccountVerifyOpt );
//6. Create Charge
var myChargeBank = new StripeChargeCreateOptions();
// amount = Returnamount.amount;
myChargeBank.Amount = int.Parse("250") * 100;
myChargeBank.Currency = "usd";
myChargeBank.CustomerId = stripeCustomer.Id;
myChargeBank.Capture = true;
StripeCharge stripeCharge = null;
stripeCharge = new StripeCharge();
var chargeService = new StripeChargeService(StripeApiKey);
stripeCharge = chargeService.Create(myChargeBank);
if (stripeCharge.Status.ToLower() == "succeeded" & stripeCharge.Paid == true) {
} else {
}
In this code, I am getting:
Stripe Exception for Verify method (bankAccountService.Verify(stripeCustomer.Id, bankAccount.Id, bankAccountVerifyOpt );)
Exception is Received unknown parameter: amounts.
on "https://github.com/jaymedavis/stripe.net#charges" implementation for 'Verify a bank account' is missing so Please help me to solve this problem so that bank account get verify successfully.

I had the same issue and I did 2 things:
1) On stripe.com, I went to my account API settings and updated them to use the lasted API.
2) I updated the Stripe.net Nuget package
After that everything worked perfectly.

Related

how to cover trigger in test class I am very new to slaesforce

trigger contacttrigger on Contact (after insert, after delete, after undelete) {
Set<Id> Ids = new Set<Id>();
if(trigger.isInsert || trigger.isUndelete){
for(Contact con:trigger.new){
if(con.Id!= null){
Ids.add(con.Id);
} } }
if(trigger.isDelete){
for(Contact con:trigger.old){
if(con.Id!= null){
Ids.add(con.Id);
}}}
if(!Ids.isEmpty()){
List<Account> accList = [SELECT Id, NoOfContacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN : Ids];
if(!accList.isEmpty()){
List<Account> updateAccList = new List<Account>();
for(Account acc:accList){
Account objAcc = new Account(Id = acc.Id, NoOfContacts__c = acc.Contacts.size());
updateAccList.add(objAcc);
}
if(!updateAccList.isEmpty()){
update updateAccList;
}
}
}
}
hello every one I am very new to salesforce Please guide me how to cover this trigger in test class thank you
You must pick report message box "SQL report service system" another on mobile site.
Triggered as Reporting Monthly.
trigger contacttrigger on Contact (after insert, after delete, after undelete) { Set Ids = new Set(); if(trigger.isInsert || trigger.isUndelete){ for(Contact con:trigger.new){ if(con.Id!= null){ Ids.add(con.Id); } } } if(trigger.isDelete){ for(Contact con:trigger.old){ if(con.Id!= null){ Ids.add(con.Id); }}} if(!Ids.isEmpty()){ List accList = [SELECT Id, NoOfContacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN : Ids]; if(!accList.isEmpty()){ List updateAccList = new List(); for(Account acc:accList){ Account objAcc = new Account(Id = acc.Id, NoOfContacts__c = acc.Contacts.size()); updateAccList.add(objAcc); } if(!updateAccList.isEmpty()){ update updateAccList; } } } }

How to send api request from test class to Main class in salesforce?

Class :
#RestResource(urlMapping='/api/fetch_status/*')
global class RestDemo{
#HttpGet
global static Account getResult(){
Account account;
String accountId = '';
RestRequest restReq = RestContext.request;
RestResponse restRes = RestContext.response;
// reading url
try{
//accountId = restReq.params.get('accountId');
accountId = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('/') + 1);
account = [SELECT Id, Name FROM Account WHERE Id = :accountId Limit 1];
if(account != null){ //checked whether any record is returned or not
restRes.responseBody = Blob.valueOf(JSON.serialize(account));
restRes.statusCode = 200;
}else{
/* String account_not_found= '{"message":"Not Found"}';
restRes.responseBody = Blob.valueOf(account_not_found); */
restRes.statusCode = 404;
}
}
catch(Exception ex){
restRes.responseBody = Blob.valueOf(ex.getMessage());
restRes.statusCode = 500;
}
return account;
}
}
Test Class :
private class RestDemoTest {
#testSetup
static void dataSetup() {
Account acc = new Account(Name = 'Testing5');
insert acc;
}
static testMethod void testGet() {
//case 1 when the id is valid
Account acc = [ SELECT Id FROM Account LIMIT 1 ];
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/api/fetch_status/' + acc.Id;
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response= res;
Account acct1 = RestDemo.getResult();
system.assertEquals(acct1.Name, 'Testing5');
// case 2 when the id is not present
String str_id = '0012x000004UjZX';
Id id = Id.valueOf(str_id);
req.requestURI = '/services/apexrest/api/fetch_status/' + id;
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response= res;
Account acct2 = RestDemo.getResult();
system.assertEquals(acct2, null);
}
}
I want to test the test case 2 where the account with the random id is not present.
But while testing the test class (in test case 2 )it is giving exception.
In this i used an existing id and changed it a little.So while test case2 runs it should go through the else statement of the main class but it is throwing exception (catch statement,Tested it in salesforce developer console).
account = [SELECT Id, Name FROM Account WHERE Id = :accountId Limit 1];
The way you written it account will never be null. It'll just throw "List has no rows for assignment to SObject".
Change to this
List<Account> accs = [SELECT Id, Name FROM Account WHERE Id = :accountId Limit 1];
if(!accs.isEmpty()){
// return 200;
} else {
// return 400;
}
If you query that way it'll always come as List. It can be empty list but it will be a list (not null). Assign query results to single Account/Contact/... only if you're 100% sure it'll return something. Or catch the exceptions

How to get Rates from UPS Rate API?

I am using nopcommerce 3.5. I have added plugin of UPS of TransitInTime and Rate API. I want to get rates by calling UPS Rate API. I want all Rates in dropdown on page load.
So for the first I am using test application using webservices of RateWebReference and in which I get only one Rate but I want Rates for all shipping option.
Here is my code of RateWSClient.cs
RateService rate = new RateService();
RateRequest rateRequest = new RateRequest();
UPSSecurity upss = new UPSSecurity();
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = "CC....";
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = "gi..";
upssUsrNameToken.Password = "Ch..";
upss.UsernameToken = upssUsrNameToken;
rate.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "Rate" };
request.RequestOption = requestOption;
rateRequest.Request = request;
ShipmentType shipment = new ShipmentType();
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = "A65V88";
RateWSSample.RateWebReference1.AddressType shipperAddress = new RateWSSample.RateWebReference1.AddressType();
String[] addressLine = { "", "", "" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "";
shipperAddress.PostalCode = "30076";
shipperAddress.StateProvinceCode = "GA";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
RateWSSample.RateWebReference1.AddressType shipFromAddress = new RateWSSample.RateWebReference1.AddressType();
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "";
shipFromAddress.PostalCode = "30076";
shipFromAddress.StateProvinceCode = "GA";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { "", "", "" };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = "";
shipToAddress.PostalCode = "92262";
shipToAddress.StateProvinceCode = "";
shipToAddress.CountryCode = "US";
shipTo.Address = shipToAddress;
shipment.ShipTo = shipTo;
CodeDescriptionType service = new CodeDescriptionType();
//Below code uses dummy date for reference. Please udpate as required.
service.Code = "02";
shipment.Service = service;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "125";
CodeDescriptionType uom = new CodeDescriptionType();
uom.Code = "LBS";
uom.Description = "pounds";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
CodeDescriptionType packType = new CodeDescriptionType();
packType.Code = "02";
package.PackagingType = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
//Shipping Rate Chart
// ShipmentRatingOptionsType SRO = new ShipmentRatingOptionsType();
//SRO.RateChartIndicator = "";
//shipment.ShipmentRatingOptions= SRO;
//rateRequest.Shipment = shipment;
ShipmentRatingOptionsType SRO = new ShipmentRatingOptionsType();
SRO.NegotiatedRatesIndicator = "";
shipment.ShipmentRatingOptions = SRO;
rateRequest.Shipment = shipment;
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
Console.WriteLine(rateRequest);
RateResponse rateResponse = rate.ProcessRate(rateRequest);
Console.WriteLine("The transaction was a " + rateResponse.Response.ResponseStatus.Description);
Console.WriteLine("Total Shipment Charges " + rateResponse.RatedShipment[0].TotalCharges.MonetaryValue + rateResponse.RatedShipment[0].TotalCharges.CurrencyCode);
Console.ReadKey();
I have resolved this questions. So If you face this kind of problem don't forget to use
String[] requestOption = { "Shop" };
in place of
String[] requestOption = { "Rate" };
Then you will get rates for all shipping options.

Error 10525 during express checkout in PayPal

I have the following code (using the Yii PHP framework):
error_reporting(E_ALL ^ E_NOTICE);
$libraryPath = Yii::getPathOfAlias('application.libraries.paypal');
spl_autoload_unregister(array('YiiBase','autoload'));
require_once($libraryPath . '/PPBootStrap.php');
spl_autoload_register(array('YiiBase','autoload'));
$PaymentDetails = new PaymentDetailsType();
$address = new AddressType();
$address->CityName = '';
$address->Name = '';
$address->Street1 = '';
$address->StateOrProvince = '';
$address->PostalCode = '';
$address->Country = '';
$address->Phone = '';
$PaymentDetails->ShipToAddress = $address;
$PaymentDetails->ShippingTotal = $PaymentDetails->HandlingTotal
= $PaymentDetails->InsuranceTotal = $PaymentDetails->TaxTotal
= new BasicAmountType('USD', 0);
$PaymentDetails->OrderTotal = $PaymentDetails->ItemTotal
= new BasicAmountType('USD', $subscription->price);
$PaymentDetails->PaymentAction = "Sale";
$PaymentDetails->OrderDescription = $subscription->description;
$setECReqDetails = new SetExpressCheckoutRequestDetailsType();
$setECReqDetails->PaymentDetails[0] = $PaymentDetails;
$setECReqDetails->CancelURL = $this->createAbsoluteUrl('adListing/listings');
$setECReqDetails->ReturnURL = $this->createAbsoluteUrl('adReturnFromPaypal');
$setECReqDetails->NoShipping = '0';
$setECReqDetails->AddressOverride = '';
$setECReqDetails->ReqConfirmShipping = '0';
$setECReqType = new SetExpressCheckoutRequestType();
$setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;
$setECReq = new SetExpressCheckoutReq();
$setECReq->SetExpressCheckoutRequest = $setECReqType;
$paypalService = new PayPalAPIInterfaceServiceService();
$ok = TRUE;
try {
Yii::trace(__METHOD__ . ': Initiating PayPal API...');
// wrap API method calls on the service object with a try catch
$setECResponse = $paypalService->SetExpressCheckout($setECReq);
if($setECResponse && strtoupper($setECResponse->Ack) =='SUCCESS') {
Yii::trace(__METHOD__ . ': Got successful response from PayPal. Redirecting to it...');
$token = $setECResponse->Token;
// Redirect to paypal.com here
$this->redirect(
'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=' . $token);
}
}
catch (Exception $ex) {
Yii::trace(__METHOD__ . ': Exception while interacting with PayPal API, error: '
. $ex->getMessage());
$ok = FALSE;
}
if (!$ok) {
Yii::app()->user->setFlash('listings', array(
'msg'=>'There was an error while interacting with PayPal. Please try again later.',
'class'=>'flash-error'));
$this->redirect(array('adListing/listings'));
}
The user is redirected to Paypal, but when they login with their sandbox account and try to pay, I get a 10525 error from Paypal:
This transaction cannot be processed. The amount to be charged is zero.
And the checkout fails. Is there a property that I'm missing to set and the process fails?
I found the problem. I forgot to include another object needed for the transaction:
$itemDetails = new PaymentDetailsItemType();
$itemDetails->Name = $subscription->description;
$itemDetails->Amount = new BasicAmountType('USD', $subscription->price);
$itemDetails->Quantity = 1;
$itemDetails->ItemCategory = 'Digital';
$PaymentDetails->PaymentDetailsItem[0] = $itemDetails;
This line
$PaymentDetails->ShippingTotal = $PaymentDetails->HandlingTotal
= $PaymentDetails->InsuranceTotal = $PaymentDetails->TaxTotal
= new BasicAmountType('USD', 0);
should also change to
$PaymentDetails->OrderTotal = $PaymentDetails->ItemTotal =
new BasicAmountType('USD', $subscription->price);

Why does this controller double the inserts when I try to archive the results of the Bing Search API?

I'm trying to archive my search results for a term by
Using the Bing API in an async controller
Inserting them into database using Entity Framework
using the Bing API and insert them into a database using entity framework. For whatever reason it is returning 50 results, but then it enters 100 results into the database.
My Controller Code:
public class DHWebServicesController : AsyncController
{
//
// GET: /WebService/
private DHContext context = new DHContext();
[HttpPost]
public void RunReportSetAsync(int id)
{
int iTotalCount = 1;
AsyncManager.OutstandingOperations.Increment(iTotalCount);
if (!context.DHSearchResults.Any(xx => xx.CityMarketComboRunID == id))
{
string strBingSearchUri = #ConfigurationManager.AppSettings["BingSearchURI"];
string strBingAccountKey = #ConfigurationManager.AppSettings["BingAccountKey"];
string strBingUserAccountKey = #ConfigurationManager.AppSettings["BingUserAccountKey"];
CityMarketComboRun cityMarketComboRun = context.CityMarketComboRuns.Include(xx => xx.CityMarketCombo).Include(xx => xx.CityMarketCombo.City).First(xx => xx.CityMarketComboRunID == id);
var bingContainer = new Bing.BingSearchContainer(new Uri(strBingSearchUri));
bingContainer.Credentials = new NetworkCredential(strBingUserAccountKey, strBingAccountKey);
// now we can build the query
Keyword keyword = context.Keywords.First();
var bingWebQuery = bingContainer.Web(keyword.Name, "en-US", "Moderate", cityMarketComboRun.CityMarketCombo.City.Latitude, cityMarketComboRun.CityMarketCombo.City.Longitude, null, null, null);
var bingWebResults = bingWebQuery.Execute();
context.Configuration.AutoDetectChangesEnabled = false;
int i = 1;
DHSearchResult dhSearchResult = new DHSearchResult();
List<DHSearchResult> lst = new List<DHSearchResult>();
var webResults = bingWebResults.ToList();
foreach (var result in webResults)
{
dhSearchResult = new DHSearchResult();
dhSearchResult.BingID = result.ID;
dhSearchResult.CityMarketComboRunID = id;
dhSearchResult.Description = result.Description;
dhSearchResult.DisplayUrl = result.DisplayUrl;
dhSearchResult.KeywordID = keyword.KeywordID;
dhSearchResult.Created = DateTime.Now;
dhSearchResult.Modified = DateTime.Now;
dhSearchResult.Title = result.Title;
dhSearchResult.Url = result.Url;
dhSearchResult.Ordinal = i;
lst.Add(dhSearchResult);
i++;
}
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
context.SaveChanges();
}
AsyncManager.Parameters["message"] = "The total number of results was "+lst.Count+". And there are " + context.DHSearchResults.Count().ToString();
}
else
{
AsyncManager.Parameters["message"] = "You have already run this report";
}
AsyncManager.OutstandingOperations.Decrement(iTotalCount);
}
public string RunReportSetCompleted(string message)
{
string str = message;
return str;
}
}
Here is how I am calling it from my asp.net mvc 4 page.
#Ajax.ActionLink("Run Report", "GatherKeywordsFromBing", "DHWebServices",
new { id=item.CityMarketComboRunID},
new AjaxOptions { OnSuccess = "ShowNotifier();", UpdateTargetId = "TopNotifierMessage", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = strCityMarketComboProgressID, LoadingElementDuration = 1000 },
new { #class = "ViewLink" })
<span class="ProgressIndicator" id="#strCityMarketComboProgressID"><img src="#Url.Content("~/Content/img/SmallBall.gif")" alt="loading" /></span>
For whatever reason all of
Try saving only once:
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
}
context.SaveChanges();
Also there's nothing asynchronous in your code, so there's no point of using asynchronous controller. Not only that it won't improve anything but it might make things worse.