Transaction ID on AuthorizeAndCapture by AuthorizedotNet - c#

I'm trying to get the transaction ID by AuthorizeAndCapture method from AuthorizeNet API.
private static void CreateTransaction(long profileId, long paymentProfileId)
{
CustomerGateway target = new CustomerGateway(ApiLogin, TransactionKey);
var response = target.AuthorizeAndCapture(profileId.ToString(), paymentProfileId.ToString(), 1020.00M);
Console.WriteLine("Hola" + response.TransactionID);
}
But, when i execute the method, the property response.TransactionID returns empty.
I tried to change from sandbox to production and doesn't works neither.

I solve the issue using another gateway of the Authorize Net
private static void CreateTransaction(long profileId, long paymentProfileId)
{
Gateway target = new Gateway(ApiLogin, TransactionKey, true);
Customer cust = new Customer {ProfileID = profileId.ToString()};
IGatewayRequest request = new AuthorizationRequest("4111111111111111", "0224", 20.10M,
"AuthCap transaction approved testing", true);
request.AddCustomer("31358164", "bla_bla#bla.com", "", "", "street", "City",
"State","256984");
const string description = "AuthCap transaction approved testing";
var actual = target.Send(request, description);
Into "actual" we found transactionID.
I hope to help others.

Related

Unit Test in Azure Function C#

I want to unit test my azure function API by sending mock request and response data. But my test is getting failed even if i pass same Json data on both request and response.
TestCode
[TestMethod]
public async Task ClinicReadTestMethod()
{
//Arrange
//var clinicRequest = new
//{
// Id = "1",
// OpenIdProvider = "Google",
// Subject = "Test",
// Name = "Test",
// Address = "Test",
// Email = "Test",
// Phone = "Test",
// Notes = "Test"
//};
var query = new Dictionary<string, StringValues>();
query.Add("openIdProvider", "Google");
query.Add("subject", "Test");
//var body = JsonSerializer.Serialize(clinicRequest);
var logger = Mock.Of<ILogger>();
var client = Mock.Of<CosmosClient>();
ContentResultFactory contentResultFactory = new ContentResultFactory();
//Act
var testFunction = new ClinicReadFunction(contentResultFactory);
var result = await testFunction.Run(TestFactory.HttpRequestSetup(query), client, logger); //fixme
var resultObject = JsonSerializer.Serialize(result as ContentResult);
//Assert
var clinicResponse = new
{
Id = "1",
openIdProvider = "Google",
subject = "Test",
Name = "Test",
Address = "Test",
Email = "Test",
Phone = "Test",
Notes = "Test"
};
var resultBody = JsonSerializer.Serialize(clinicResponse);
//var res = contentResultFactory.CreateContentResult(HttpStatusCode.OK);
Assert.AreEqual(resultBody, resultObject);
}
}
This is how my azure function looks like. It is taking two parameters and returning the response. I have tried to mock the data for unit test still no success. If anyone have idea how to unit test this azure function please let me know.
//AzureFunction
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "")] HttpRequest req,
[CosmosDB(
databaseName: "",
containerName: "",
Connection = ""
)] CosmosClient client,
ILogger log)
{
string subject = req.Query["sub"];
if (!Enum.TryParse(req.Query["idp"], out OpenIdProvider openIdProvider) || string.IsNullOrEmpty(subject))
{
var message = "";
log.LogWarning();
return _contentResultFactory.CreateContentResult(message, HttpStatusCode.BadRequest);
}
var query = client.GetContainer("", "").GetItemLinqQueryable<Clinic>()
.Where(x => x.OpenIdProvider == openIdProvider && x.Subject == subject);
Clinic clinic;
using (var iterator = query.ToFeedIterator())
clinic = (await iterator.ReadNextAsync()).FirstOrDefault();
if (clinic == null)
{
log.LogWarning();
return _contentResultFactory.CreateContentResult();
}
var response = new ClinicReadResponse(clinic);
return _contentResultFactory.CreateContentResult(response, HttpStatusCode.OK);
}
//TestFactory
public static HttpRequest HttpRequestSetup(Dictionary<string, StringValues> query)
{
var context = new DefaultHttpContext();
var request = context.Request;
request.Query = new QueryCollection(query);
request.Method = "GET";
return request;
}
In both your Clinic objects, your are generating a new GUID for the ID by calling System.Guid.NewGuid. Assuming the JSON generated from each object is the same shape (they will need to be if you want them to match), the values of each ID property will be different. Since the IDs are different, your JSON strings are not equal, therefore causing the failure.
Here is a post that will show you how to manually create a Guid. You can use this to ensure your IDs are of the same value when testing.
Assigning a GUID in C#
I don't know what your Azure Function code looks like, but your test's setup to make an HTTP request tells me you're calling the method tied to the Http Trigger. Consider the scope of what your method is doing; if it is large (or is calling other methods), this will increase the chances of your test breaking as you change the Azure Function over time. To help future-proof your test make sure the method it's calling has a single responsibility. This will make debugging your code easier to do if a change does make your test fail, and will lessen the likelihood of needing to edit your test to accommodate for code changes.

Error in PayPal Chained Adaptive Payments

After two days of testing, googling and so on, I decided to write here. I'm sorry for my bad English :)
I downloaded the PayPal Adaptive Payments SDK for .NET from http://paypal.github.io/sdk/#adaptive-payments and I opened the solution with Visual Studio Ultimate 2012 to try the samples. Unfortunately the Chained example doesn't works, with the following error:
Invalid request parameter: action type PAY_PRIMARY can only be used in chained payments
I studied documentation and tried several changes, without any result.
I created new project with this code https://devtools-paypal.com/guide/ap_chained_payment/dotnet?interactive=ON&env=sandbox
My code is
ReceiverList receiverList = new ReceiverList();
receiverList.receiver = new List<Receiver>();
Receiver secondaryReceiver = new Receiver((decimal?)1.00);
secondaryReceiver.email = "platfo_1255170694_biz#gmail.com";
secondaryReceiver.primary = false;
secondaryReceiver.paymentType = "SERVICE";
receiverList.receiver.Add(secondaryReceiver);
Receiver primaryReceiver = new Receiver((decimal?)2.00);
primaryReceiver.email = "platfo_1255612361_per#gmail.com";
primaryReceiver.primary = true;
primaryReceiver.paymentType = "GOODS";
primaryReceiver.invoiceId = "123456789";
receiverList.receiver.Add(primaryReceiver);
RequestEnvelope requestEnvelope = new RequestEnvelope("it_IT");
string actionType = "PAY";
string returnUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?success=true";
string cancelUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?cancel=true";
string currencyCode = "EUR";
PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
payRequest.ipnNotificationUrl = "http://replaceIpnUrl.com";
payRequest.feesPayer = "PRIMARYRECEIVER";
payRequest.trackingId = "123456789";
Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
sdkConfig.Add("mode", "sandbox");
sdkConfig.Add("account1.apiUsername", "jb-us-seller_api1.paypal.com");
sdkConfig.Add("account1.apiPassword", "WX4WTU3S8MY44S7F");
sdkConfig.Add("account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31A7yDhhsPUU2XhtMoZXsWHFxu-RWy");
sdkConfig.Add("account1.applicationId", "APP-80W284485P519543T");
AdaptivePaymentsService service = new AdaptivePaymentsService(sdkConfig);
PayResponse response = service.Pay(payRequest);
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" + response.payKey;
}
I tried to set the property feesPayer to PRIMARYRECEIVER with the following error:
The fee payer PRIMARYRECEIVER can only be used if a primary receiver is specified
The Request of this code is
requestEnvelope.errorLanguage=it_IT&
actionType=PAY
cancelUrl=https://devtools-paypal.com/guide/ap_chained_payment/dotnet?cancel=true&
currencyCode=EUR&
feesPayer=PRIMARYRECEIVER&
ipnNotificationUrl=http://replaceIpnUrl.com&
receiverList.receiver(0).amount=1&
receiverList.receiver(0).email=platfo_1255170694_biz#gmail.com&
receiverList.receiver(0).primary=False&
receiverList.receiver(0).paymentType=SERVICE&
receiverList.receiver(1).amount=2&
receiverList.receiver(1).email=platfo_1255612361_per#gmail.com&
receiverList.receiver(1).primary=True&
receiverList.receiver(1).invoiceId=123456789&
receiverList.receiver(1).paymentType=GOODS&
returnUrl=https://devtools-paypal.com/guide/ap_chained_payment/dotnet?success=true&
trackingId=123456789&
The Response is
responseEnvelope.timestamp=2014-05-08T09:05:04.204-07:00&
responseEnvelope.ack=Failure&
responseEnvelope.correlationId=1a4d172eb110d&
responseEnvelope.build=10680030&
error(0).errorId=580023&
error(0).domain=PLATFORM&
error(0).subdomain=Application&
error(0).severity=Error&
error(0).category=Application&
error(0).message=The fee payer PRIMARYRECEIVER can only be used if a primary receiver is specified&
error(0).parameter(0)=feesPayer&
error(0).parameter(1)=PRIMARYRECEIVER
The line primaryReceiver.primary = true; in my C# code seems not to work... any ideas please? Has anyone had this type of problem?
Thank you in advance.

LinkedIn OAUTH - Still can't get email-address using DotNetOpenAuth.AspNet

Having read that since late last year LinkedIn finally have finally allowed us to retrieve the email address for the currently logged on user I've been failing to do so. I've read all the posts I can find on SO and elsewhere and as far as I can tell my code should be working. It returns just fine with all the other fields,
however, the email address field is always empty.
Here's my LinkedInClient class;
public class LinkedInClient2 : OAuthClient
{
public static readonly ServiceProviderDescription LinkedInServiceDescription = new ServiceProviderDescription
{
AccessTokenEndpoint =
new MessageReceivingEndpoint(
"https://api.linkedin.com/uas/oauth/accessToken",
HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
RequestTokenEndpoint =
new MessageReceivingEndpoint(
"https://api.linkedin.com/uas/oauth/requestToken?scope=r_basicprofile+r_emailaddress",
HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
UserAuthorizationEndpoint =
new MessageReceivingEndpoint(
"https://www.linkedin.com/uas/oauth/authenticate",
HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
ProtocolVersion = ProtocolVersion.V10a
};
public LinkedInClient2(string consumerKey, string consumerSecret, IConsumerTokenManager tokenManager)
: base("linkedIn", LinkedInServiceDescription, tokenManager)
{
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care if the request fails.")]
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
{
// See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014
const string ProfileRequestUrl = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,headline,industry,summary,picture-url)";
string accessToken = response.AccessToken;
var profileEndpoint = new MessageReceivingEndpoint(ProfileRequestUrl, HttpDeliveryMethods.GetRequest);
HttpWebRequest request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken);
try
{
using (WebResponse profileResponse = request.GetResponse())
{
using (Stream responseStream = profileResponse.GetResponseStream())
{
XDocument document = LoadXDocumentFromStream(responseStream);
string userId = document.Root.Element("id").Value;
// User Profile Fields - https://developer.linkedin.com/documents/profile-fields
string firstName = document.Root.Element("first-name").Value;
string lastName = document.Root.Element("last-name").Value;
string userName = document.Root.Element("email-address").Value; // <<<<<< ERROR - always empty
var extraData = new Dictionary<string, string>();
extraData.Add("accesstoken", accessToken);
extraData.Add("name", userName);
extraData.AddDataIfNotEmpty(document, "picture-url");
extraData.AddDataIfNotEmpty(document, "location");
extraData.AddDataIfNotEmpty(document, "headline");
extraData.AddDataIfNotEmpty(document, "summary");
extraData.AddDataIfNotEmpty(document, "industry");
return new AuthenticationResult(
isSuccessful: true, provider: this.ProviderName, providerUserId: userId, userName: userName, extraData: extraData);
}
}
}
catch (Exception exception)
{
return new AuthenticationResult(exception);
}
}
internal static XDocument LoadXDocumentFromStream(Stream stream)
{
const int MaxChars = 0x10000; // 64k
XmlReaderSettings settings = new XmlReaderSettings()
{
MaxCharactersInDocument = MaxChars
};
return XDocument.Load(XmlReader.Create(stream, settings));
}
}
}
I realise that I'm supposed to add the scope=r_emailaddress to the RequestTokenEndpoint (which I have) but from the fiddler traces I can't even see that endpoint being fetched. Basically, it only every uses the AccessTokenEndpoint which presumably is something to do with my problem.
This is approximately how my ASP.Net MVC4.5 controller looks;
[AllowAnonymous]
public virtual ActionResult LinkedIn(string returnUrl)
{
var tokenMgr = new RepoOAuthTokenManager(_iOtk, LinkedInAppKey, LinkedInAppSecret);
var iacp = new LinkedInClient2(LinkedInAppKey, LinkedInAppSecret, tokenMgr); // if none specified, LinkedInClient uses the AuthenticationOnlyCookieOAuthTokenManager which doesn't work for APIs
var ioadp = new MyOauthDataProvider();
var oasm = new OpenAuthSecurityManager(this.HttpContext, iacp, ioadp);
var redirectUri = Url.ActionFullyQualified(this.nameof(c => c.LinkedIn(null)), null, new RouteValueDictionary(new { returnUrl = returnUrl }));
AuthenticationResult ar = oasm.VerifyAuthentication(redirectUri);
if (ar.Error == null)
{
if (ar.IsSuccessful)
DoSomethingResultingInRedirect(redirectUri); // OK
else
oasm.RequestAuthentication(redirectUri);
}
else
ModelState.AddModelError("", ar.Error.Message);
return View(this.nameof(c=>c.Login(null)));
}//LinkedIn
I can't say I completely understand the extensibility mechanism in DotNetOpenAuth and I may be misunderstanding something so I'd appreciate some pointers.
Am I missing a step somewhere?
I have two solutions to this, although I still don't understand how to get my existing code to work as I'd expect, but hopefully this may help someone else;
(1) I went to Making it easier for you to add default member permissions and clicked on the API admin page.
Here you can select what scopes you want requested by default. It didn't work until I clicked a box (now disappeared) that was worded along the lines of "[x] Make this permanent". Once I'd done that I started to get the email-address field populated as I was expecting.
(2) I tried using the OAuth2 URL instead from information here and it seemed to work. I have also found an implementation of an OAuth2 client here which looks like a good start. I suspect that in the long run, an OAuth2 upgrade (once the spec is more static) will yield better overall mileage.
For now though, I'm out of the pit of despair, but other answers are still welcome!
I had a similar issue.. maybe this is relevant for you:
My Request Token Call is:
https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,member-url-resources,picture-url,location,public-profile-url,email-address)?format=json
but the json response is:
array(8) {
["emailAddress"]=>
string(18) "email#email.com"
["firstName"]=>
string(3) "Tim"
...
Note that in the first case email is named email-address, in the second emailAddress.

Rally API: Adding Users to a Project

I'm new to the Rally world and am struggling through how to use the RallyRestAPI. There are a number of examples of how to query Rally to get back pertinent information that I have found most helpful. What I'm trying to do is create a C# command line tool to add users to a project. It appears that I use the RallyRestAPI.Create("projectpermission",some dynamic json object) interface to accomplish the creation. My problem is understanding the "some dynamic json object" part. I'm not sure how to correctly set it up. If someone has a small example of how to set it up, I would appreciate it.
Here's a code sample illustrating how to do this. Note that:
UserID running the code to create permissions must be a Workspace or Subscription Administrator
User must already have permissions in the Workspace (i.e be a Workspace User) in order for the ProjectPermission creation to succeed
namespace RestExample_AddUsersToProject {
class Program
{
static void Main(string[] args)
{
String userName = "user#company.com";
String userPassword = "topsecret";
String serverUrl = "https://rally1.rallydev.com";
String wsapiVersion = "1.38";
RallyRestApi restApi = new RallyRestApi(
userName,
userPassword,
serverUrl,
wsapiVersion
);
restApi.Headers[RallyRestApi.HeaderType.Vendor] = "Rally Software";
restApi.Headers[RallyRestApi.HeaderType.Name] = "RestExample_AddUsersToProject";
// Query for Project for which we want to add permissions
Request projectRequest = new Request("project");
projectRequest.Fetch = new List<string>()
{
"Name",
"Owner",
"State",
"Description"
};
String projectName = "Avalanche Hazard Mapping";
projectRequest.Query = new Query("Name", Query.Operator.Equals, projectName);
QueryResult queryProjectResults = restApi.Query(projectRequest);
var myProject = queryProjectResults.Results.First();
String myProjectReference = myProject["_ref"];
Console.WriteLine("Project Name: " + myProject["Name"]);
Console.WriteLine("State: " + myProject["State"]);
// Query for User for whom we wish to add ProjectPermission
Request userRequest = new Request("user");
userRequest.Fetch = new List<string>()
{
"UserName",
"Subscription",
"DisplayName"
};
// User needing the permissions
userRequest.Query = new Query("UserName", Query.Operator.Equals, "\"boromir#midearth.com\"");
QueryResult queryUserResults = restApi.Query(userRequest);
var myUser = queryUserResults.Results.First();
String myUserReference = myUser["_ref"];
Console.WriteLine("Username: " + myUser["UserName"]);
Console.WriteLine("Display Name: " + myUser["DisplayName"]);
Console.WriteLine("Subscription: " + myUser["Subscription"]);
// Setup required ProjectPermission data
DynamicJsonObject newProjectPermission = new DynamicJsonObject();
newProjectPermission["User"] = myUser;
newProjectPermission["Project"] = myProject;
newProjectPermission["Role"] = "Editor";
// Create the permission in Rally
CreateResult addProjectPermissionResult = restApi.Create("ProjectPermission", newProjectPermission);
DynamicJsonObject fetchedProjectPermission = restApi.GetByReference(addProjectPermissionResult.Reference, "Name");
Console.WriteLine("Created ProjectPermission with Role: " + fetchedProjectPermission["Name"]);
}
}
}
There are some very basic examples of CRUD + querying here:
http://developer.rallydev.com/help/rest-api-net
The general flow will always be to create a new DynamicJsonObject, set the appropriate fields and then pass that object to the Create method of an RallyRestApi.

using google oauthutill in a desktop application to retrieve contacts

I am using oauth to get acces to google contacts from a desktop application. I have followed the instruction from google here: http://code.google.com/intl/iw-IL/apis/gdata/docs/auth/oauth.html#Examples but I am having problems
here is the code:
OAuthParameters parameters = new OAuthParameters()
{
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
Scope = SCOPE,
Callback = "http://localhost:10101/callback.htm.txt",
SignatureMethod = "HMAC-SHA1"
};
OAuthUtil.GetUnauthorizedRequestToken(parameters);
string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
Console.WriteLine(authorizationUrl);
var win = new GoogleAuthenticationWindow(authorizationUrl,parameters);
win.ShowDialog();
OAuthUtil.GetAccessToken(parameters);
inside the window I have the following:
private void BrowserNavigated(object sender, NavigationEventArgs e)
{
if (e.Uri.ToString().Contains("oauth_verifier="))
{
OAuthUtil.UpdateOAuthParametersFromCallback(e.Uri.ToString(), m_parameters);
Close();
}
}
at the last line (OAuthUtil.GetAccessToken(parameters);) I am getting a 400 bad request error and I have no idea why...
After much playing around... I think this is the easiest way to access google api:
Service service = new ContactsService("My Contacts Application");
service.setUserCredentials("mail#gmail.com", "password");
var token = service.QueryClientLoginToken();
service.SetAuthenticationToken(token);
var query = new ContactsQuery(#"https://www.google.com/m8/feeds/contacts/mail#gmail.com/full?max-results=25000");
var feed = (ContactsFeed)service.Query(query);
Console.WriteLine(feed.Entries.Count);
foreach (ContactEntry entry in feed.Entries)
{
Console.WriteLine(entry.Title.Text);
}
much easier than using oauth...

Categories

Resources