Capture payment Paypal - paypal

This is the code i used for capture payments in Paypal
OAuthTokenCredential tokenCredential = new OAuthTokenCredential("<CLIENT_ID>", "<CLIENT_SECRET>");
var accessToken = tokenCredential.GetAccessToken();
Authorization authorization = Authorization.Get(accessToken, "5RA45624N3531924N");
Capture capture = new Capture();
Amount captureAmount = new Amount();
captureAmount.currency = "USD";
captureAmount.total = "1";
capture.amount = captureAmount;
capture.is_final_capture = true;
Capture responseCapture = authorization.Capture(accessToken, capture);
But it says
Argument type 'string' is not assignable to parameter type 'PayPal.Api.APIContext'
in following line accessToken parameter
Authorization authorization = Authorization.Get(accessToken, "5RA45624N3531924N");
How can i solve this issue?

Create a new class 'Configuration.cs'.
public static class Configuration
{
public readonly static string ClientId;
public readonly static string ClientSecret;
static Configuration()
{
var config = GetConfig();
ClientId = config["clientId"];
ClientSecret = config["clientSecret"];
}
public static Dictionary<string,string> GetConfig()
{
return PayPal.Api.ConfigManager.Instance.GetProperties();
}
private static string GetAccessToken()
{
var config = GetConfig();
OAuthTokenCredential credential = new OAuthTokenCredential(ClientId, ClientSecret, config);
string accessToken = credential.GetAccessToken();
return accessToken;
}
public static APIContext GetAPIContext()
{
string accessToken = GetAccessToken();
APIContext apiContext = new APIContext(accessToken);
apiContext.Config = GetConfig();
return apiContext;
}
}
GetAPIContext method will return APIContext object. Pass that object as a parameter to Authorization.Get method instead of "accessToken".
APIContext apiContext = Configuration.GetAPIContext();
Authorization authorization = Authorization.Get(apiContext, "6SY29185GS4409204");//Provide Payment Id returned after authorizing payment.

You specified the token in the first parameter, it's not correct.
According to below definition:
public static Authorization Get(APIContext apiContext, string authorizationId)
You should specify APIContext type.
Can you try the code like below:
var apiContext = Configuration.GetAPIContext();
var authorization = Authorization.Get(apiContext, authorizationId);

Related

Is there a way to register a data asset in Azure Data Catalog via api without user-login?

My app gets a token and can make api calls to the ADC like searching. But the request for registration of new asset fails, because the field "LastRegisterdBy" must not be null/empty and has to correspond to current user.
However the token does not contain any user information (AccessToken().Result.UserInfo.DisplayableId is null).
I mostly followed the get started get-started project MS provides (https://github.com/Azure-Samples/data-catalog-dotnet-get-started/blob/master/Program.cs)
But i use
AcquireTokenAsync(resourceUri, clientCredential).ConfigureAwait(false)
instead of
AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always)).
This so nobody has to enter his credentials. The goal is to run the code in ssis package, which will execute on a weekly basis to catch any updates in the data automatically.
This is the outline of my code:
class Program
{
static string clientIDFromAzureAppRegistration = "";
static string clientSecret = "";
static AuthenticationResult authResult = null;
static string catalogName = "catalog";
static void Main(string[] args)
{
var authResult = AccessToken();
string upn = authResult.Result.UserInfo.DisplayableId;
var id = RegisterDataAsset(authResult, SampleJson("test", upn));
}
static async Task<AuthenticationResult> AccessToken()
{
if (authResult == null)
{
//Resource Uri for Data Catalog API
string resourceUri = "https://api.azuredatacatalog.com";
//To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID
string clientId = clientIDFromAzureAppRegistration;
string clientS = clientSecret;
// Create an instance of AuthenticationContext to acquire an Azure access token
var authority = "https://login.microsoftonline.com/52497ec2-0945-4f55-8021-79766363dd96";
var authContext = new AuthenticationContext(authority);
var clientCredential = new ClientCredential(clientId, clientS);
// Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
// AcquireToken takes a Client Id that Azure AD creates when you register your client app.
authResult = await authContext.AcquireTokenAsync(resourceUri, clientCredential).ConfigureAwait(false);
}
return authResult;
}
static string RegisterDataAsset(Task<AuthenticationResult> authResult, string json){
...
}
static HttpWebResponse SetRequestAndGetResponse(HttpWebRequest request, Task<AuthenticationResult> authResult, string payload = null){
...
}
static string SampleJson(string name, string upn){
...}
With upn = authResult.Result.UserInfo.DisplayableId; i get:
{"error":{"code":"InvalidPropertyValue","message":"Invalid input value for one of the properties. Path: 'properties.lastRegisteredBy.upn'. Details: Value cannot be null, empty or consists entirely of whitespaces."}}
Wit upn = "test#user":
{"error":{"code":"InvalidLastRegisteredBy","message":"LastRegisteredBy is different from the current user."}}
I found the solution, its quite simple:
The user-name of the app is: clientIDFromAzureAppRegistration + "#" + tenantId.

Authorize attribute authorizing any JWT token for the controller in asp.net core?

I am trying to use JWT authentication in my ASP.NET CORE project.
Step-1: I have added the JWT service in ConfigureServices method of Starup.cs file.
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
RequireExpirationTime = true,
ValidateLifetime = true,
ValidateAudience = false,
ValidateActor = false,
ValidateIssuer = false
};
});
And added below code in the Configure method:
app.UseAuthentication();
Step-2: Sending the jwt token while login.
public class LoginRepository
{
public LoginRepository()
{
//TODO: Dependency to MongoDB will be initialized here
}
public LoginStatus Authenticate(string username, string password)
{
LoginStatus loginStatus = new LoginStatus();
string secretKey = ConfigurationManager.AppSetting["Jwt:SecretKey"];
int tokenExpirationHours = int.Parse(ConfigurationManager.AppSetting["Jwt:TokenExpirationHours"]);
//TODO: Need to add the userID in the payload. UserID will come from Database
Dictionary<string, string> payload = new Dictionary<string, string>() {
{ "UserName", username}
};
//TODO: Need to check the username and password in Database and then generate the token
loginStatus.Token = JwtTokenHelper.GenerateJwtToken(secretKey, payload, tokenExpirationHours);
return loginStatus;
}
}
Here is the JwtTokenHelper:
public class JwtTokenHelper
{
public static string GenerateJwtToken(string secretKey, IReadOnlyDictionary<string, string> payloadContents, int tokenExpirationHours)
{
JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
var payloadClaims = payloadContents.Select(c => new Claim(c.Key, c.Value));
var payload = new JwtPayload("", "", payloadClaims, DateTime.Now, DateTime.Now.AddHours(tokenExpirationHours));
var header = new JwtHeader(signingCredentials);
var securityToken = new JwtSecurityToken(header, payload);
return jwtSecurityTokenHandler.WriteToken(securityToken);
}
}
Here, I am getting the JWT token successfully.
Step-3: Now, I tried to authorize a controller and it is working nice when I have given the token in the Authorization header from Postman.
namespace SampleAPI.Controllers
{
[Authorize]
[Produces("application/json")]
[Route("api/Test")]
public class TestController : Controller
{
[HttpGet]
[Route("Testing")]
public IActionResult Testing()
{
return Ok("Yes");
}
}
}
But, if I change something in the JWT token and again hit this endpoint, it is returning "Yes" means it is saying that the jwt token is valid. But I have changed some parts of that token before sending in the Authorization header.
What am I missing here? Can you please point me out what more steps should I follow?

How to create a SOAP request in EWS?

I've got such kind of class with required login, password, url and domain:
class Service
{
public ExchangeService service;
public void Connect()
{
const string exchangeUser = "login";
const string exchangePassword = "password";
const string exchangeUri = "url";
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.UseDefaultCredentials = true;
service.Credentials = new WebCredentials(exchangeUser, exchangePassword, "domain");
service.Url = new Uri(exchangeUri);
}
}
And I need to add such method as CreateAppointment()
public void CreateAppointment()
{
Appointment appointment = new Appointment(service);
appointment.Subject = "Team building exercise";
appointment.Body = "Let's learn to really work as a team and then have lunch!";
appointment.Start = DateTime.Now.AddHours(2);
appointment.End = appointment.Start.AddHours(4);
appointment.Location = "Some city";
appointment.RequiredAttendees.Add("somebody#something.com");
appointment.ReminderMinutesBeforeStart = 30;
appointment.Save(SendInvitationsMode.SendToNone);
}
Save() method doesn't work because of some reasons for creating service and appointment objects. So I need to rewrite this method using xml request. And I've got an example of SOAP request from msdn https://msdn.microsoft.com/en-us/library/office/dd633661(v=exchg.80).aspx
How could I insert the SOAP request instead of CreateAppointment() method? I've got no idea what to do with xml code to make it work as CreateAppointment() method.

Signing AWS Api Gateway request in Unity3D C#

I'm using Unity3D v5.5.1, with AWS-SDK-Unity v3.3.37.0.
Since the Api Gateway doesn't generate an SDK for C#/Unity3D I'm trying to sign (SigV4) the request my self and have encountered difficulties.
I've tried both manually signing and using the AWS4Signer.cs class.
The Api Gateway method has the Invoke with caller credentials, and just returns a Hello World as a response.
Within unity I have a facebook login button which returns the FB credentials and tokens. Using Cognito Federated Identity's GetCredentialsAsync method I get an ImmutableCredentials object with the Key, Secret and a Token.
To access the api gateway url I'm using the AWS4Signer class here to construct a signed request. In the example below I've tried both adding the security token to the url parameters and without, also signing it and not signing with the token. All options don't work (As stated in this post)
This results in either the following responses:
1. The request signature we calculated does not match the signature you provided
The security token included in the request is invalid.
How can I correctly sign the request from Unity3D?
Thanks in advance
TestGet method:
IEnumerator TestGet (ImmutableCredentials response)
{
ApiGatewayConfig clientConfig = new ApiGatewayConfig(); // a class I created wrapping the ClientConfig.cs
var metrics = new RequestMetrics();
var awsAccessKeyId = response.AccessKey;
var awsSecretAccessKey = response.SecretKey;
var awsToken = response.Token;
AmazonWebServiceRequest req = new MyRequest(); // a clas I created wrapping the AmazonWebServiceRequest.cs class
var url = "https://<url_to_api>.execute-api.us-east-1.amazonaws.com/dev/securehello";
IRequest request = new DefaultRequest(req,"execute-api");
request.UseQueryString = true;
request.HttpMethod = "GET";
request.Endpoint = new System.Uri (url);
request.ResourcePath = url;
request.ContentStream = new MemoryStream();
request.Parameters.Add("X-Amz-Expires",AWS4PreSignedUrlSigner.MaxAWS4PreSignedUrlExpiry.ToString(CultureInfo.InvariantCulture));
request.AuthenticationRegion = "us-east-1";
request.AlternateEndpoint = RegionEndpoint.USEast1;
request.UseSigV4 = true;
request.Headers.Add("X-Amz-Security-Token",awsToken);
request.Parameters.Add("X-Amz-Security-Token",awsToken);
AWS4Signer signer = new AWS4Signer();
Debug.Log ("a");
signer.Sign(request,clientConfig,metrics,awsAccessKeyId,awsSecretAccessKey);
var signerRes = signer.SignRequest(request,clientConfig,metrics,awsAccessKeyId,awsSecretAccessKey);
Debug.Log ("b");
var myParams = string.Format("{0}&X-Amz-Security-Token={1}",signerRes.ForQueryParameters,awsToken);
var dict = myParams.Split('&').Select(p=> p.Split('=')).GroupBy(p => p[0]).Select(p => p.First()).ToDictionary(p => p[0], p=>System.Uri.UnescapeDataString(p[1]));
var myEncodedParams = string.Empty;
bool isFirst = true;
foreach (var key in dict.Keys) {
myEncodedParams += string.Format("{0}{1}={2}",isFirst ? "" : "&",key,WWW.EscapeURL(dict[key]));
isFirst = false;
}
var finalUrl = string.Format ("{0}?{1}", request.Endpoint.AbsoluteUri,myEncodedParams);
UnityWebRequest uwr = new UnityWebRequest (finalUrl, "GET", new DownloadHandlerBuffer (), null);
Debug.Log ( string.Format("\n\n\n{0}\n\n\n",finalUrl));
Debug.Log ("Starting WebRequest");
yield return uwr.Send();
if (uwr.isError) {
Debug.LogError (uwr.error);
} else {
Debug.Log (uwr.downloadHandler.text);
}
Helper classes:
public class ApiGatewayConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.37.0");
private string _userAgent = UserAgentString;
public ApiGatewayConfig ()
{
this.AuthenticationServiceName = "execute-api";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "execute-api";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2015-07-09";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
public class MyRequest : AmazonWebServiceRequest
{
public MyRequest () {}
}
Solved.
I've created some examples showing how to do this. Still work in progress, example shows how to sign a POST request from Unity 3D to Api Gateway endpoint that has "Invoke with caller credentials" (AWS_IAM).
Unity 3D Client:
https://github.com/guywald/serverless-auth-msg-board-unity3d-client
AWS Serverless backend (using Serverless Framework):
https://github.com/guywald/serverless-auth-msg-board

OAuthRequestValidator Access Token and Access Token Secret

I am trying to add an account to QuickBooks Online using Intuit IPP:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0200_DevKits_for_Intuit_Partner_Platform/0100_IPP_.NET_DevKit/Query_Filters/QuickBooks_Online
How do I get the access token and the access token secret? Here is my code:
class Program
{
static string appToken = "xxx";
static string oAuthConsumerKey = "xxx";
static string oAuthConsumerSecret = "xxx";
static void Main(string[] args)
{
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(appToken, "", oAuthConsumerKey, oAuthConsumerSecret);
ServiceContext context = new ServiceContext(oauthValidator, appToken, "1234", IntuitServicesType.QBD);
DataServices dataServices = new DataServices(context);
Account account = new Account();
account.Desc = "TEST PLEASE DELETE";
string guid = Guid.NewGuid().ToString("N");
guid = guid.Substring(0, 30);
account.Name = guid;
account.Type = Intuit.Ipp.Data.Qbd.AccountTypeEnum.Liability;
account.TypeSpecified = true;
account.Subtype = "Accounts Payable";
Account resultAccount = dataServices.Add(account) as Account;
}
}
I figured it out. Look at step 6 here:
http://ippblog.intuit.com/blog/2012/09/ode-to-oauth-and-rest-apis-and-how-i-love-thee-not.html
Joseph,
For Future reference and for others the documentation for your question is located here:
IPP Oauth Documentation
regards,
Jarred