GithubHelp home page GithubHelp logo

cybersource / cybersource-rest-client-dotnet Goto Github PK

View Code? Open in Web Editor NEW
18.0 13.0 44.0 44.62 MB

.NET client library for the CyberSource REST API

License: Other

C# 99.26% Shell 0.02% Batchfile 0.06% Mustache 0.66%

cybersource-rest-client-dotnet's Introduction

.NET Client SDK for the CyberSource REST API

Description

The CyberSource .NET client provides convenient access to the CyberSource REST API from your .NET application.

System Requirements

  • .NET Framework 4.6.1

Installation

  • Nuget Package Manager
PM>  Install-Package CyberSource.Rest.Client

Account Registration and Configuration

  • Account Registration

Follow the first step mentioned in Getting Started with CyberSource REST SDKs to create a sandbox account.

  • Configuration

Follow the second step mentioned in Getting Started with CyberSource REST SDKs to configure the SDK by inputting your credentials.

Please note that this is for reference only. Ensure to store the credentials in a more secure manner.

How to Use

To get started using this SDK, it's highly recommended to download our sample code repository:

In that respository, we have comprehensive sample code for all common uses of our API:

Additionally, you can find details and examples of how our API is structured in our API Reference Guide:

The API Reference Guide provides examples of what information is needed for a particular request and how that information would be formatted. Using those examples, you can easily determine what methods would be necessary to include that information in a request using this SDK.

Example using Sample Code Application

For more detailed examples, refer to the cybersource-rest-samples-csharp repository.

Switching between the sandbox environment and the production environment

Cybersource maintains a complete sandbox environment for testing and development purposes. This sandbox environment is an exact duplicate of our production environment with the transaction authorization and settlement process simulated. By default, this SDK is configured to communicate with the sandbox environment. To switch to the production environment, set the runEnvironment property in the SDK Configuration. See our sample at the Configuration.cs class in the Sample Codes repository.

    // For TESTING use
    _configurationDictionary.Add("runEnvironment", "apitest.cybersource.com");
    // For PRODUCTION use
    // _configurationDictionary.Add("runEnvironment", "api.cybersource.com");

API credentials are different for each environment, so be sure to switch to the appropriate credentials when switching environments.

Logging

Generic badge

Since v0.0.1.14, a new logging framework has been introduced in the SDK. This new logging framework makes use of NLog, and standardizes the logging so that it can be integrated with the logging in the client application.

More information about this new logging framework can be found in this file : Logging.md

Features

MetaKey Support

A Meta Key is a single key that can be used by one, some, or all merchants (or accounts, if created by a Portfolio user) in the portfolio.

The Portfolio or Parent Account owns the key and is considered the transaction submitter when a Meta Key is used, while the merchant owns the transaction.

MIDs continue to be able to create keys for themselves, even if a Meta Key is generated.

Further information on MetaKey can be found in New Business Center User Guide.

OAuth Support

OAuth enables service providers to securely share access to customer data without sharing password data.

The CyberSource OAuth2.0 Authorization Server (or API Auth Service) will issue access tokens (based on merchant user credentials) to CyberSource or third-party Applications. These applications can access CyberSource APIs on the merchant's behalf, using the access tokens.

During application registration, third-party application developers are issued a client_id and optionally a client_secret (if they can be considered a confidential client, for example a web application).

These values will be used when the merchant application wants to request an access token and/or a refresh token. This is explained in more detail in Requesting the Access and Refresh Tokens.

For more detailed information on OAuth, refer to the documentation at Cybersource OAuth 2.0.

In order to use OAuth, set the run environment to OAuth enabled URLs. OAuth only works in these run environments.

    // For TESTING use
    _configurationDictionary.Add("runEnvironment", "api-matest.cybersource.com")
    // For PRODUCTION use
    // _configurationDictionary.Add("runEnvironment", "api-ma.cybersource.com")

Additional Information

IMPORTANT FOR v0.0.1.30, v0.0.1.31, v0.0.1.32

CyberSource is aware of an issue with these versions of the SDK caused by the tight coupling of the version of RestSharp with the SDK. The packaging information has not been updated to reflect the correct constraints for RestSharp.

This issue will get resolved from the upcoming version onwards.

To resolve the issue in these three versions, run the following command from the Package Manager Console:

Install-Package RestSharp -Version 108.0.3

You may also want to execute the following command to upgrade the Authentication SDK to the correct version:

Install-Package CyberSource.Authentication -Version 0.0.0.16

How to Contribute

  • Fork the repo and create your branch from master.
  • If you've added code that should be tested, add tests.
  • Ensure the test suite passes.
  • Submit your pull request! (Ensure you have synced your fork with the original repository before initiating the PR).

Need Help?

For any help, you can reach out to us at our Discussion Forum.

Disclaimer

CyberSource may allow Customer to access, use, and/or test a CyberSource product or service that may still be in development or has not been market-tested (“Beta Product”) solely for the purpose of evaluating the functionality or marketability of the Beta Product (a “Beta Evaluation”). Notwithstanding any language to the contrary, the following terms shall apply with respect to Customer’s participation in any Beta Evaluation (and the Beta Product(s)) accessed thereunder): The Parties will enter into a separate form agreement detailing the scope of the Beta Evaluation, requirements, pricing, the length of the beta evaluation period (“Beta Product Form”). Beta Products are not, and may not become, Transaction Services and have not yet been publicly released and are offered for the sole purpose of internal testing and non-commercial evaluation. Customer’s use of the Beta Product shall be solely for the purpose of conducting the Beta Evaluation. Customer accepts all risks arising out of the access and use of the Beta Products. CyberSource may, in its sole discretion, at any time, terminate or discontinue the Beta Evaluation. Customer acknowledges and agrees that any Beta Product may still be in development and that Beta Product is provided “AS IS” and may not perform at the level of a commercially available service, may not operate as expected and may be modified prior to release. CYBERSOURCE SHALL NOT BE RESPONSIBLE OR LIABLE UNDER ANY CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE RELATING TO A BETA PRODUCT OR THE BETA EVALUATION (A) FOR LOSS OR INACCURACY OF DATA OR COST OF PROCUREMENT OF SUBSTITUTE GOODS, SERVICES OR TECHNOLOGY, (B) ANY CLAIM, LOSSES, DAMAGES, OR CAUSE OF ACTION ARISING IN CONNECTION WITH THE BETA PRODUCT; OR (C) FOR ANY INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES INCLUDING, BUT NOT LIMITED TO, LOSS OF REVENUES AND LOSS OF PROFITS.

License

This repository is distributed under a proprietary license.

cybersource-rest-client-dotnet's People

Contributors

akshunyainfy avatar brianmc avatar chsriniv9 avatar gaubansa avatar gnongsie avatar monu-kumar-visa avatar snavinch avatar ssethumavisa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cybersource-rest-client-dotnet's Issues

API Contracts are not correct - Required parameters allowing NULL

There are many areas in the API which are not designed properly. For instance this file:

https://github.com/CyberSource/cybersource-rest-client-dotnet/blob/master/Api/ReportsApi.cs

You can see that startTime, endTime are required in SearchReportsAsyncWithHttpInfo. However the method signature allows nullable datetime fields as defined here:

public async System.Threading.Tasks.Task<ApiResponse> SearchReportsAsyncWithHttpInfo (DateTime? startTime, DateTime? endTime, string timeQueryType, string organizationId = null, string reportMimeType = null, string reportFrequency = null, string reportName = null, int? reportDefinitionId = null, string reportStatus = null)

The correct method signature should be this:

public async System.Threading.Tasks.Task<ApiResponse> SearchReportsAsyncWithHttpInfo (DateTime startTime, DateTime endTime, string timeQueryType, string organizationId = null, string reportMimeType = null, string reportFrequency = null, string reportName = null, int? reportDefinitionId = null, string reportStatus = null)

SearchReportsWithHttpInfo vs SearchReportsAsyncWithHttpInfo incomplete code within SearchReportsWithHttpInfo

In SearchReportsAsyncWithHttpInfo you have the following code:

// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
  "application/json;charset=utf-8"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

But in the non-async version (SearchReportsWithHttpInfo ) it seems it was forgot to be set:

// to determine the Content-Type header  
String[] localVarHttpContentTypes = new String[] {  
   "application/json;charset=utf-8"  
};  
String localVarHttpContentType = "";  

Is this stuff not getting code reviewed?

Where are the unit tests for this stuff?

KeyGenerationApi / GeneratePublicKey Request is missing model data

The KeyGenerationApi uses a model called GeneratePublicKeyRequest. The GeneratePublicKeyRequest is missing the "targetOrigin" field.

As you can see this field is required for proper flex form creation and is available in the API indicated here:

http://apps.cybersource.com/library/documentation/dev_guides/hosted_flex/0_1_0/html/custom-server-integration/

However there is a documentation bug where it doesn't list it as a valid field in the Flex area here:

https://developer.cybersource.com/api/reference/api-reference.html

targetOrigin is infact a valid field.

There are two issues that need to be addressed here:

  1. Your API documentation located here is incorrect:
    https://developer.cybersource.com/api/reference/api-reference.html

  2. Your .NET REST client is not correct as a result, the GeneratePublicKeyRequest request object needs that field added or you can not use the generated keys within the Flex Microform.

Here is the API that needs to be updated with the new field:

https://github.com/CyberSource/cybersource-rest-client-dotnet/blob/d235961f9ce586fbfdf75a58b1efe8cb5fa0a690/Api/KeyGenerationApi.cs

Charge Back Detail Report

Are you going to add support for the Charge Back Detail Report?

It would be very similar to the Purchase and Refund report, with the same parameters, servlet call and structure is almost identical

ApiClient.Deserialize has magic strings and should be removed

There is code like this:

if (type.Name.StartsWith("System.Nullable`1[[System.DateTime"))

Which is not good way to do it as it is magic string and bloats framework code.

It should be this:

if ( type == typeof(DateTime?))

What about regular DateTime (non nullable)?

Dependencies such as RestSharp are not present in the Nuget package

When I pull in the cybersource-rest-client nuget package for this SDK into a new project and attempt to use the Configuration class I get a class initializer error "The type initializer for 'CyberSource.Client.Configuration' threw an exception." File Not Found for RestSharp. Seems like the RestClient timeout at line 112 is the issue. https://github.com/CyberSource/cybersource-rest-client-dotnet/blob/master/Client/Configuration.cs#L112

Does the Nuget package need to pull in it's dependent packages on install?

Incorrect data types on TmsV1InstrumentIdentifiersPaymentInstrumentsGet200Response

TmsV1InstrumentIdentifiersPaymentInstrumentsGet200Response has the following incorrect datatypes:

    [DataMember(Name = "offset", EmitDefaultValue = false)]
    public string Offset { get; }
    [DataMember(Name = "limit", EmitDefaultValue = false)]
    public string Limit { get; }
    [DataMember(Name = "count", EmitDefaultValue = false)]
    public string Count { get; }
    [DataMember(Name = "total", EmitDefaultValue = false)]
    public string Total { get; }

All of those should be integers "int".

GetTransactionBatchDetails

I got it to work by changing the type on the call from void to ApiResponse

I tested two batches, one was a small ACH batch with a couple hundred transactions, the other was a large Credit Card batch that had around 4,000 transactions. The larger batch threw an error.

Is it possible it is simply timing out on the larger file, if so how do I increase the time-out

XML Documentation in Nuget package

Please can you generate the XML documentation file (Project Properties -> Build -> XML documentation file) on build and include it in the nuget package such that the comments are published with the library? This would make the api much easier to use without needing to clone the git repo.

Thanks

"Hello World" sample throws NullReferenceException in the REST client

The same code on https://developer.cybersource.com/hello-world.html simply fails with a NullReferenceException when the CreatePayment call gets made. Configuration is setup to use HTTP_SIGNATURE on the sandbox.

Here is the stack trace where it throws the exception:

   at CyberSource.Client.ApiClient.CallAuthenticationHeaders(String requestType, String requestTarget, String requestJsonData)
   at CyberSource.Client.ApiClient.PrepareRequest(String path, Method method, Dictionary`2 queryParams, Object postBody, Dictionary`2 headerParams, Dictionary`2 formParams, Dictionary`2 fileParams, Dictionary`2 pathParams, String contentType)
   at CyberSource.Client.ApiClient.CallApi(String path, Method method, Dictionary`2 queryParams, Object postBody, Dictionary`2 headerParams, Dictionary`2 formParams, Dictionary`2 fileParams, Dictionary`2 pathParams, String contentType)
   at CyberSource.Api.PaymentsApi.CreatePaymentWithHttpInfo(CreatePaymentRequest createPaymentRequest)
   at CyberSource.Api.PaymentsApi.CreatePayment(CreatePaymentRequest createPaymentRequest)

How can I generate PtsV2PaymentsPost400Response from failed PaymentAPI

If I make a payment, via the PaymentsAPI that results in a failure, buy default the error is wrapped in an exception and the api response is just a string making up part of the message.
If I set the ExceptionFactory to null, I then get an actual response form CreatePayment or CreatePaymentWithHttpInfo but this is of type PtsV2PaymentsPost201Response so it does not include the reason for the error.

Is there support to return PtsV2PaymentsPost400Response with the reason, or is this futures work?

Error Deserializing TransactionDetailsApi response (TssV2TransactionsGet200Response)

Full error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1
[CyberSource.Model.TssV2TransactionsGet200ResponseMerchantDefinedInformation]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'merchantDefinedInformation', line 1, position 774.

In the response the merchantDefinedInformation class is null. The point referred to in the JSON is:
..."fraudMarkingInformation":{},"merchantDefinedInformation":{},"merchantInformation":...

Commenting out the merchantDefinedInformation references in the TssV2TransactionsGet200Response I'm able to retrieve the transaction.

Unit tests in this project are all empty / only stubbed out...

This library would be much better if it had unit tests. The unit tests that exist appear to be empty shells and do not do anything.

I have found so many bugs in this project that I bet more than half would have been already resolved if proper unit tests were created.

Please test your library more thoroughly.

Documentation for CyberSource.Model.CreateSearchRequest particularly the Query property.

May I please get some more documentation on how to use the Query property of CyberSource.Model.CreateSearchRequest?

Both
https://github.com/CyberSource/cybersource-rest-client-dotnet/blob/master/docs/CreateSearchRequest.md
and
https://github.com/CyberSource/cybersource-rest-client-dotnet/blob/master/Api/SearchTransactionsApi.cs
are lacking when it comes to the mechanics of supplying ranges as
shown in the sample here:
https://github.com/CyberSource/cybersource-rest-samples-csharp/blob/master/src/Samples/TransactionSearch/CoreServices/CreateSearchRequest.cs

where
Query = "clientReferenceInformation.code:TC50171_3 AND submitTimeUtc:[NOW/DAY-7DAYS TO NOW/DAY+1DAY}",

I can discern that CreateSearch() returns
a TssV2TransactionsPost201Response which contains a collection of
TssV2TransactionsPost201ResponseEmbeddedTransactionSummaries
and that the search query property acts on nested properties such as ClientReferenceInformation.code with a dot notation and uses camel casing.

What is not clear in this sample is the "submitTimeUtc:[NOW/DAY-7DAYS TO NOW/DAY+1DAY}"
How am I supposed to know this syntax?
What does the "[" signify?
What does the "}" signify?
What type of language is this?

Where may I find the documentation please?

License isn't clear

It's not clear if this SDK is presented as open source copy-left, open for contribution, or free to use/manipulate/distribute.

Please consider MIT or another more open license.

Transaction Search API not working as documented

There is an undocumented “feature” in your Transaction Search API.

https://developer.cybersource.com/api/reference/api-reference.html

According to above URL it indicates that only 201, 400, 502 should be valid response codes.

For successful responses it is infact 201.

However for a search on a merchant reference code (clientReferenceInformation.code) that does not exist, it returns a 404 error response. With data indicating there was nothing found (count:0 in response JSON).

This doesn't seem to be proper API design, as 404 indicates errors in most frameworks / librarys and should not be used to mean "not found" of a search request. Even in your .NET REST client in this GIT repo it fails to parse this response properly and throws an exception.

Is this an API design bug since it isn't documented?

Can you fix the .NET REST client to behave properly in this condition and return the response body without throwing an exception?

Example in LIVE CONSOLE showing this issue:

image

Critical Bug in DownloadReportAsyncWithHttpInfo

In the DownloadReportAsyncWithHttpInfo class when requesting a report you do not get any report data back!

I decompiled your library and found the issue.

I have highlighted issue in RED:

image

If you look at the non async version you get this:

image

You are missing restResponse.get_Content()!!!!

You are requesting everyone to convert to new REST Report download by 7/31/2019, but have such critical bug to disallow async function???

SearchReportsWithHttpInfo is completely broken

This is related to #40 and #44. I spent several hours debugging this issue and found that the wrong data model is being used to return the data.

SearchReportsWithHttpInfo attempts to deserialize the data as follows:

return new ApiResponse<ReportingV3ReportsGet200Response>(localVarStatusCode,
                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (ReportingV3ReportsGet200Response) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ReportingV3ReportsGet200Response)));

The problem is ReportingV3ReportsGet200Response is not defined correctly.

I have defined a variant that is correct and will return data.

The key point is that Reports array should be "reportSearchResults" as that is what is defined in the REST api. You have it defined as "reports". A whole new model should be made called ReportingV3ReportSearchGet200Response. I have given you the proper code below:

namespace ARRT.Payments.Services.Models.Reports
{
    public class Links
    {
        public Self Self { get; set; }
    }

    public class Self
    {
        public string href { get; set; }
    }

    [DataContract]
    public partial class ReportingV3ReportSearchGet200Response : IEquatable<ReportingV3ReportsGet200Response>, IValidatableObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ReportingV3ReportsGet200Response" /> class.
        /// </summary>
        /// <param name="Reports">Reports.</param>
        public ReportingV3ReportSearchGet200Response(List<ReportingV3ReportsGet200ResponseReports> Reports = default(List<ReportingV3ReportsGet200ResponseReports>))
        {
            this.Reports = Reports;
        }

        [DataMember(Name = "_links", EmitDefaultValue = false)]
        public Links Links { get; set; }

        /// <summary>
        /// Gets or Sets Reports
        /// </summary>
        [DataMember(Name = "reportSearchResults", EmitDefaultValue = false)]
        public List<ReportingV3ReportsGet200ResponseReports> Reports { get; set; }

        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class ReportingV3ReportSearchGet200Response {\n");
            sb.Append("  Reports: ").Append(Reports).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as ReportingV3ReportsGet200Response);
        }

        /// <summary>
        /// Returns true if ReportingV3ReportsGet200Response instances are equal
        /// </summary>
        /// <param name="other">Instance of ReportingV3ReportsGet200Response to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(ReportingV3ReportsGet200Response other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.Reports == other.Reports ||
                    this.Reports != null &&
                    this.Reports.SequenceEqual(other.Reports)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                if (this.Reports != null)
                    hash = hash * 59 + this.Reports.GetHashCode();
                return hash;
            }
        }

        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            yield break;
        }
    }
}

I then made my own version of SearchReportsWithHttpInfo that has the following method signature:

      private ApiResponse<ReportingV3ReportSearchGet200Response> SearchReportsWithHttpInfo(Configuration Configuration, DateTime? startTime, DateTime? endTime, string timeQueryType, 
                    string organizationId = null, string reportMimeType = null, string reportFrequency = null, string reportName = null, 
                    int? reportDefinitionId = null, string reportStatus = null)

It returns the following:

            return new ApiResponse<ReportingV3ReportSearchGet200Response>(localVarStatusCode,
                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (ReportingV3ReportSearchGet200Response)Configuration.ApiClient.Deserialize(localVarResponse, typeof(ReportingV3ReportSearchGet200Response)));

I now have data! This client library package needs a lot of testing and updates before it is production ready. How are customers suppose to comply with 7/31/2019 REST API Reporting transition when this stuff is completely broken?

Cleanup Compilation Warnings

Fix the following compilation warnings:

1>C:\TFS\cybersource-rest-client-dotnet-0.0.0.8\Model\ErrorResponse.cs(57,28,57,34): warning CS0109: The member 'ErrorResponse.ToJson()' does not hide an accessible member. The new keyword is not required.
1>C:\TFS\cybersource-rest-client-dotnet-0.0.0.8\Model\PaymentInstrumentsArray.cs(57,28,57,34): warning CS0109: The member 'PaymentInstrumentsArray.ToJson()' does not hide an accessible member. The new keyword is not required.
1>C:\TFS\cybersource-rest-client-dotnet-0.0.0.8\Model\ErrorResponseWithHAL.cs(57,28,57,34): warning CS0109: The member 'ErrorResponseWithHAL.ToJson()' does not hide an accessible member. The new keyword is not required.
1>C:\TFS\cybersource-rest-client-dotnet-0.0.0.8\Model\PersonalIdentificationArray.cs(57,28,57,34): warning CS0109: The member 'PersonalIdentificationArray.ToJson()' does not hide an accessible member. The new keyword is not required.
1>  cybersource-rest-client-dotnet -> C:\TFS\cybersource-rest-client-dotnet-0.0.0.8\bin\Debug\cybersource-rest-client-dotnet.dll
2>------ Build started: Project: cybersource-rest-client-dotnet.Test, Configuration: Debug Any CPU ------
2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "Newtonsoft.Json" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
2>  cybersource-rest-client-dotnet.Test -> C:\TFS\cybersource-rest-client-dotnet-0.0.0.8\test\bin\Debug\CyberSource.Test.dll

ApiClient.Deserialize unnecessarily writes to TempFolderPath?

In looking at ApiClient.Deserialize it appears that you are writing to file system, just to read back again. Why not just return MemoryStream? Is the thought to try reduce memory footprint?

When do you delete the temp file? Or will our hard drives eventually fill with these temp files?

Also the santifizefilename doesn't seem to account for different types of operating environments such as Windows, Linux, OSX such as in Windows which doesn't allow certain characters in file name.

TransactionExceptionDetailReport_Daily_Classic gives error when no data available

The new REST API's when pulling the classic reports are giving error with cybersource-rest-client-dotnet.

When requesting for instance the following report: TransactionExceptionDetailReport_Daily_Classic

We get the following error:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<errorBean>
    <code>RESOURCE_NOTFOUND</code>
    <detail>The requested resource is not found. Please try again later.</detail>
    <localizationKey>cybsapi.resource.notfound</localizationKey>
    <message>Requested Resource Not Found</message>
</errorBean>

However on old reporting API it provides a report with no records (indicating to us that the report was infact published, but that there was no data, and our QC checks can complete). In your new reporting platform it doesn't work, but yet you want folks to transition to the new playform by 7/31/2019? We can transition with all these bugs. See here for more bugs #36 #37

Here is what we get under old reporting API successfully for the same date and merchant account:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Report SYSTEM "https://ebc.cybersource.com/ebc/reports/dtd/tedr_1_1.dtd">
<Report Name="Transaction Exception Detail" 
        Version="1.1" 
        xmlns="https://ebc.cybersource.com/ebc/reports/dtd/tedr_1_1.dtd" 
        MerchantID="xyz" 
        ReportStartDate="2019-06-26T07:00:00-07:00" 
        ReportEndDate="2019-06-27T07:00:00-07:00">
  <Requests></Requests>
</Report>

How to perform integration testing, or override hostname or baseurl

I'm trying to write an integration test for come client code that uses this SDK, for the test, I want the API request to hit an internal (in the test process) http endpoint. whilst one of the constructors for ApiClient hint this can be done, in practice when you make an api call (like PaymentApi CreatePayment) there is a call to CallAuthenticationHeaders and this creates a MerchantConfig (from the authentication sdk), which can only use one of 2 runEnvironments to derive a hostname, that CallAuthenticationHeaders uses to construct a new RestClient:
e.g.: RestClient = new RestClient("https://" + merchantConfig.HostName);

I can't seam to override HostName, is there anyway to do this? (this is an integration test not unit, so I want a real http request)

ApiClient.cs MerchantConfig Not Being Reset Properly

We are currently utilizing the CyberSource API to pull user info using the UserManagementApi. We need to pull our user listing for multiple merchants. So we plan on loading all of the merchants with their corresponding API keys and looping through and calling the UserManagementAPI.

This is how that looks:

Retrieve Users from Merchants

Dim Merchants As List(Of Merchant) = New List(Of Merchant)

Dim merch1 As New Merchant With {.MerchantID = "xxxxxxx", .SerialNumber = "xxxxxxx", .SecretKey = "xxxxxxx="}
Dim merch2 As New Merchant With {.MerchantID = "xxxxxxx", .SerialNumber = "xxxxxxx", .SecretKey = "xxxxxxx"}
Dim merch3 As New Merchant With {.MerchantID = "xxxxxxx", .SerialNumber = "xxxxxxx", .SecretKey = "xxxxxxx"}

Merchants.Add(merch1)
Merchants.Add(merch3)
Merchants.Add(merch2)

ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

For Each Merchant In Merchants
    Dim ConfigDictionary As Dictionary(Of String, String) = New Configuration().GetConfiguration(MerchantID:=Merchant.MerchantID,SecretKey:=Merchant.SecretKey, SerialNumber:=Merchant.SerialNumber)
    Dim ClientConfig As Client.Configuration = New CyberSource.Client.Configuration(merchConfigDictObj:=ConfigDictionary)
    Dim APIInstance As Api.UserManagementApi = New CyberSource.Api.UserManagementApi(ClientConfig)

    Dim ConfigDictionary As Dictionary(Of String, String) = New Configuration().GetConfiguration()
    Dim ClientConfig As Client.Configuration = New CyberSource.Client.Configuration(merchConfigDictObj:=ConfigDictionary)
    Dim APIInstance As Api.UserManagementApi = New CyberSource.Api.UserManagementApi(ClientConfig)
    Dim Result = As Model.UmsV1UsersGet200Response = APIInstance.GetUsers(organizationId:=Merchant .MerchantID)

''' Process results
Next

Configuration class

Public Class Configuration
    Private _configurationDictionary As New Dictionary(Of String, String)

    Public Function GetConfiguration(ByVal MerchantID As String, ByVal SecretKey As String, ByVal SerialNumber As String) As Dictionary(Of String, String)
        _configurationDictionary.Add("authenticationType", "HTTP_SIGNATURE")
        _configurationDictionary.Add("merchantID", MerchantID)
        _configurationDictionary.Add("merchantsecretKey", SecretKey)
        _configurationDictionary.Add("merchantKeyId", SerialNumber)
        ''_configurationDictionary.Add("keysDirectory", "Resource")
        _configurationDictionary.Add("runEnvironment", "cybersource.environment.production")

        Return _configurationDictionary

    End Function
End Class

This works great for the first merchant in the list but once we get to the second, we get an unauthorized 401 code even though we can validate that it works if we put it in the beginning of the list.

What I believe is happening is when we call UserManagementApi.cs initially we will set this

// ensure API client has configuration ready
            if (Configuration.ApiClient.Configuration == null)
            {
                this.Configuration.ApiClient.Configuration = this.Configuration;
            }

However, on the second call of the UserManagementApi when we are ready to process the next merchant Configuration.ApiClient.Configuration is already set therefore we don't reset it with the new configuration for the new merchant.

That becomes an issue when we get to ApiClient.cs to get the merchant config and generate the authentication header as we start populating it with the previous merchant id which causes the 401 not authorized to return.

var merchantConfig = Configuration.MerchantConfigDictionaryObj != null
                ? new MerchantConfig(Configuration.MerchantConfigDictionaryObj)
                : new MerchantConfig();


........

//generate signature and set HTTP Signature headers
                var httpSign = authorize.GetSignature();
                authenticationHeaders.Add("v-c-merchant-id", httpSign.MerchantId);

Not sure if this is by design or an issue, but we were able to get around this by adding the following line of code to ensure that Configuration.ApiClient.Configuration gets reset.

ClientConfig.ApiClient.Configuration = Nothing '' Set to nothing to ensure we reset
Dim Merchants As List(Of Merchant) = New List(Of Merchant)

Dim merch1 As New Merchant With {.MerchantID = "xxxxxxx", .SerialNumber = "xxxxxxx", .SecretKey = "xxxxxxx="}
Dim merch2 As New Merchant With {.MerchantID = "xxxxxxx", .SerialNumber = "xxxxxxx", .SecretKey = "xxxxxxx"}
Dim merch3 As New Merchant With {.MerchantID = "xxxxxxx", .SerialNumber = "xxxxxxx", .SecretKey = "xxxxxxx"}

Merchants.Add(merch1)
Merchants.Add(merch3)
Merchants.Add(merch2)

ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

For Each Merchant In Merchants
    Dim ConfigDictionary As Dictionary(Of String, String) = New Configuration().GetConfiguration(MerchantID:=Merchant.MerchantID,SecretKey:=Merchant.SecretKey, SerialNumber:=Merchant.SerialNumber)
    Dim ClientConfig As Client.Configuration = New CyberSource.Client.Configuration(merchConfigDictObj:=ConfigDictionary)
    Dim APIInstance As Api.UserManagementApi = New CyberSource.Api.UserManagementApi(ClientConfig)

    Dim ConfigDictionary As Dictionary(Of String, String) = New Configuration().GetConfiguration()
    Dim ClientConfig As Client.Configuration = New CyberSource.Client.Configuration(merchConfigDictObj:=ConfigDictionary)
    ClientConfig.ApiClient.Configuration = Nothing '' Set to nothing to ensure we reset
    Dim APIInstance As Api.UserManagementApi = New CyberSource.Api.UserManagementApi(ClientConfig)
    Dim Result = As Model.UmsV1UsersGet200Response = APIInstance.GetUsers(organizationId:=Merchant .MerchantID)

''' Process results
Next

Library is marked Pre-Release but required to switch to REST API for Report Downloads by 7/31/2019

Hi,

This library is marked Pre-Release, and I have found bugs. But Cybersource is requesting all customers witch to REST API for all report downloads due to decommissioning of old endpoint by 7/31/2019.

It seems you guys are a bit premature in decommissioning old interface until you get stable librarys for all platforms?

Here is the notice when you login to business center:

If you haven’t yet begun switching to the new reports and the new REST APIs, please consider planning to make the switch now. If you do not update your implementation to access the new reports and data via the REST APIs, you will have to manually access all reports and data once legacy access methods (servlets) are retired on July 31st, 2019.

If you perform any of the following actions today, you will be impacted: 

• Search for Transactions by Merchant Reference Number or Request ID using Single Transaction Query 
• Download reports of any kind such as the Payment Batch Detail Report, the Transaction Detail Report, or the Decision Manager Detail Report 
• Download reply.all, reply.rejected, or au.response.pan files 
• Perform any other function described in the Migration Guide (https://apps.cybersource.com/library/documentation/dev_guides/reporting_and_reconciliation/Servlet_to_REST_Migration.pdf) 

Below are reference materials to help you get you started: 

- Reporting Documentation (https://www.cybersource.com/developers/documentation/reporting_and_reconciliation/ 
- Reporting Migration Guide (http://apps.cybersource.com/library/documentation/dev_guides/reporting_and_reconciliation/Reporting_Migration.pdf) 
- Servlet to REST Migration Guide (https://apps.cybersource.com/library/documentation/dev_guides/reporting_and_reconciliation/Servlet_to_REST_Migration.pdf)

Please contact your Customer Support representatives for any questions you may have about this change. 

Thank You, 
CyberSource Customer Support

TransactionSearchAPI - Not getting back the right number of TransactionSummaries

Hi.
When I am doing the TransactionSearch in some cases I am not getting back the number of expected Transaction Summaries.

For instance this search result says that there are 5 records returned - but there are only 4 in the Embedded.TransactionSummaries. The one that I am missing is the 1 that has the expected OrderInformation and PaymentInformation.

?result
{class TssV2TransactionsPost201Response {
SearchId: 93a8559b-2b5a-4c38-9f1b-6f6c916ba5b6
Save: False
Name: TSS search
Timezone: America/Phoenix
Query: clientReferenceInformation.code:19095 AND submitTimeUtc:[NOW/DAY-7DAYS TO NOW/DAY+1DAY}
Offset: 0
Limit: 100
Sort: id:asc, submitTimeUtc:asc
Count: 5
TotalCount: 5
SubmitTimeUtc: 2020-08-03T23:30:04Z
Embedded: class TssV2TransactionsPost201ResponseEmbedded {
TransactionSummaries: System.Collections.Generic.List1[CyberSource.Model.TssV2TransactionsPost201ResponseEmbeddedTransactionSummaries] } ?result {class TssV2TransactionsPost201Response { SearchId: 93a8559b-2b5a-4c38-9f1b-6f6c916ba5b6 Save: False Name: TSS search Timezone: America/Phoenix Query: clientReferenceInformation.code:19095 AND submitTimeUtc:[NOW/DAY-7DAYS TO NOW/DAY+1DAY} Offset: 0 Limit: 100 Sort: id:asc, submitTimeUtc:asc Count: 5 TotalCount: 5 SubmitTimeUtc: 2020-08-03T23:30:04Z Embedded: class TssV2TransactionsPost201ResponseEmbedded { TransactionSummaries: System.Collections.Generic.List1[CyberSource.Model.TssV2TransactionsPost201ResponseEmbeddedTransactionSummaries]
}

Structure incompatibility when deserilizing transaction details response.

The response returned from a transaction detail request sent to "cybersource.environment.sandbox" has an "orderInformation.billTo" structure that contains a string property for "company" rather than JSON structure compatible with "Ptsv2paymentsOrderInformationBillToCompany". For our tests to complete successfully, we changed the Company property on "TssV2TransactionsGet200ResponseOrderInformationBillTo" to be a string for now. We're concerned about this mismatch. Are we encountering a server API version compatibility issue or should the REST client be updated to support both potential response formats? (Related to #25)

Unable to make more than 1 call to the Api Client due to flaw in authentication header generation

If you attempt to make more than one call with this library it will bomb due to authentication failures upon the 2nd call.

I traced the flaw to the way the authentication header is being generated. It is not generated on each call to the api methods, it only generates 1 time. This causes subsequent calls to fail as the proper authentication header is not sent with the request.

The only known work around to this bug is to keep re-initializing the configuration object and the various api clients (such as SearchTransactionsApi). Please fix this as it's crazy you can't call a method more than once.

In the attached code example run CybersourceBrokenExample1(); I have already provided our test environment keys so it will hopefully be easier for you to run. Feel free to put in your own merchant keys.

CybersourceBrokenExample2(); is another example of a typical usage case where you get more details on a transaction after getting results. This also fails due to invalid authentication headers being sent.

ConsoleApp1.zip

Invalid parameter "OrganizationId"

Hello,

Since the last update, we have errors while calling ConversionReport with the following error :
"Invalid parameter organizationId".
After some investigations, we have figured out this was caused by the organizationId parameter being added to the request URL.
This parameter is optional and therefore should not be present if empty. The same request without the parameter succeeds just fine.

Link to generate keys in requires incorrect

The link for keys under requirements leads to a 404 on sample apps.

On this repo, it simply links to the test account page, but there is no clarity on which type of key is required to make this SDK function.

GetTransactionBatches Unauthorized

The GetTransactionBatches call returns a 401.

Using the Developer portal, my credentials work correctly. Executing within this client, a 401 is returned. Even using the generated sample code from the portal below inside of the samples project the same result is returned. The GetConfiguration() dictionary works successfully with other calls. Just not this one.

var startTime = DateTime.ParseExact("2019-04-11T22:47:57Z", "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
var endTime = DateTime.ParseExact("2019-05-01T22:47:57Z", "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);

var configDictionary = new Configuration().GetConfiguration();
var clientConfig = new CyberSource.Client.Configuration(merchConfigDictObj: configDictionary);
var apiInstance = new TransactionBatchesApi(clientConfig);

var result = apiInstance.GetTransactionBatches(startTime, endTime);
Console.WriteLine(result);

SearchReports broken, gives 404 when calling

Here is my code:

var result = reportApiSearch.SearchReports(reportDate, reportDate, "reportTimeFrame");

image

Stack Trace:

   at CyberSource.Api.ReportsApi.SearchReportsWithHttpInfo(Nullable`1 startTime, Nullable`1 endTime, String timeQueryType, String organizationId, String reportMimeType, String reportFrequency, String reportName, Nullable`1 reportDefinitionId, String reportStatus)
   at CyberSource.Api.ReportsApi.SearchReports(Nullable`1 startTime, Nullable`1 endTime, String timeQueryType, String organizationId, String reportMimeType, String reportFrequency, String reportName, Nullable`1 reportDefinitionId, String reportStatus)
   at ARRT.Payments.Services.Vendors.CyberSource.CyberSourceGateway.<DownloadReport>d__1.MoveNext() in C:\TFS\ARRT.All.Projects\ARRT.Payments.Services\Vendors\CyberSource\CyberSourceGateway.cs:line 61

Error: A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)

We use CyberSource in our software as a payment processor. Our assemblies are all signed. Our solution is unable to make the API calls to CyberSource to the newly provided dlls because they are not signed. The errors/Exception is detailed below along with screenshots.

Could not load file or assembly 'cybersource-rest-client-dotnet, Version=0.0.0.7, Culture=neutral, PublicKeyToken=null' or one of its dependencies into strongly named projects (C#). Seems like I need a signed dll to fix this, else my project throws an error as in attached screenshot.
image

I tried signing the solution provided in the GitHub (cybersource-rest-client-dotnet) to see if my code updates to the new API calls would work, but then it failed again because a dll (AuthenticationSdk, Version=0.0.0.4) was not signed (screenshot attached)
image.

Hope to get a quick resolution to this issue.

Thanks,

Raj

Payment API has missing properties required for 3DS Implementation

When using the Payments API with combined Consumer Authentication, I have found that certain fields are missing from the request and response objects.
https://developer.cybersource.com/api-reference-assets/index.html#payments_payments

To successfully submit a 3DS request with Authorisation I had to modify the following files and add additional properties:

Model/PtsV2PaymentsPost201ResponseConsumerAuthenticationInformation.cs

[DataMember(Name = "accessToken", EmitDefaultValue = false)]
public string AccessToken { get; set; }

Model/Ptsv2paymentsConsumerAuthenticationInformation.cs
[DataMember(Name = "returnUrl", EmitDefaultValue = false)]
public string ReturnUrl { get; set; }

TransactionSeachAPI - Cybersource Error Converting Value

Hi. After I have done the search I am using the record to then call the GetTransaction.
In at least 1 instance that I know of, it is failing with this exception.

?exception.Message
"Error converting value "The Golf Center" to type 'CyberSource.Model.Ptsv2paymentsOrderInformationBillToCompany'. Path 'orderInformation.billTo.company', line 1, position 963."

exception.Source
"cybersource-rest-client-dotnet"

?exception.StackTrace
" at CyberSource.Client.ApiClient.Deserialize(IRestResponse response, Type type)\r\n at CyberSource.Api.TransactionDetailsApi.GetTransactionWithHttpInfo(String id)\r\n at CyberSource.Api.TransactionDetailsApi.GetTransaction(String id)

Thank you

Add Flex Key verification routine to this library

Currently this library provides a way to get Flex Keys (albeit incorrectly since it is missing the targetOrigin model property as indicated in #60).

What would be great is if it also had the Verify function that is found in the FlexServerSDK (which has a major bug that crashes IIS App Pools due to the crazy AppDomain code it interacts with that to this date has not been fixed).

That way we have a raw http library that can retrieve and verify flex tokens and there would be no need for that FlexServerSDK nuget project (which doesn't have a github btw to report bugs!!!)

billTo_middleName is missing from the Request Fields

When creating a customer token for a payment card (via this API), I would like to include billTo_middleName in the request . Currently, this field is missing from the Request Fields. Is there a way to make this happen?

Thanks!

Provide Open API 3.0 (swagger) files

It would be really nice if Cybersource provided Open API 3.0 files for all your API end points.

That way we could just generate our own client code as this library has many bugs, is not .NET Standard compatible, and is not actively maintained (many pending pull requests, open issues, and missing unit tests)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.