Подтвердить что ты не робот

Использование банковских счетов с помощью Authorize.Net С# SDK

После игры с образцом кода CIF XML API С# для авторизованного использования я начал использовать Authorize.Net С# SDK. Я могу добавить кредитные карты и банковские счета в профили клиентов, используя пример кода CIM XML API. Я не вижу, как добавить банковские счета, используя SDK, хотя.

Добавление банковского счета в XML-API CIM:

...
customerPaymentProfileType new_payment_profile = new customerPaymentProfileType();
paymentType new_payment = new paymentType();

bankAccountType new_bank = new bankAccountType();
new_bank.nameOnAccount = "xyz";
new_bank.accountNumber = "4111111";
new_bank.routingNumber = "325070760";
new_payment.Item = new_bank;

new_payment_profile.payment = new_payment;

createCustomerPaymentProfileRequest request = new createCustomerPaymentProfileRequest();
XmlAPIUtilities.PopulateMerchantAuthentication((ANetApiRequest)request);

request.customerProfileId = profile_id.ToString();
request.paymentProfile = new_payment_profile;
request.validationMode = validationModeEnum.testMode;
...

Используя SDK, я вижу только метод .AddCreditCard(), но никак не могу добавить банковский счет. Когда я прохожу через все мои PaymentProfiles, он выдает исключение, когда он встречается с банковским счетом:

CustomerGateway cg = new CustomerGateway("xxx", "yyy");

foreach (string cid in cg.GetCustomerIDs())
{
    Customer c = cg.GetCustomer(cid);
    foreach (PaymentProfile pp in c.PaymentProfiles)
    {
        Console.WriteLine(pp.ToString());
    }
}

Исключение:

Unable to cast object of type 'AuthorizeNet.APICore.bankAccountMaskedType' to type 'AuthorizeNet.APICore.creditCardMaskedType'.

enter image description here

Как добавить банковскую учетную запись в профиль CIM с помощью SDK Authorize.Net С#?

Update:

Доказательство того, что CIM может хранить информацию о банковском счете:

enter image description here

4b9b3361

Ответ 1

Протестировано следующее, но только по мере того, как был поднят исходный вопрос (проверьте его больше для меня?), я написал его, используя предоставленный пример XML, и скопировав код для кода AddCreditCard.

Когда все будет сделано, будет обновлен следующий код:

        var cg = new CustomerGateway("login", "transkey", ServiceMode.Test);
        var c = cg.CreateCustomer("[email protected]", "test customer");
        //just to show that we didn't break CC
        cg.AddCreditCard(c.ProfileID, "cc#", 07, 2011);
        cg.AddBankAccount(c.ProfileID, "Peter", "bankaccoung#", "routing#");
        //tostring doesn't actually do much... but if you break on it you can see the details for both the CC and the bank info.
        foreach (PaymentProfile pp in cg.GetCustomer(c.ProfileID).PaymentProfiles)
        {
            Console.WriteLine(pp.ToString());
        }

Сначала загрузите исходный код С# для API из http://developer.authorize.net/downloads/.

При просмотре кода я могу видеть 4 файла, которые используют "creditCardType", это SubscriptionRequest.cs, CustomerGateway.cs, PaymentProfile.cs и AnetApiSchema.cs(это последнее, что нам не нужно касаться). Нам также нужно следить за "creditCardMaskedType", который используется в PaymentProfile.cs, Transaction.cs и AnetApiSchema.cs. В любом месте, где появляются эти файлы, мы должны убедиться, что мы также поддерживаем равноценности bankAccount.

Откройте решение AuthorizeNET. Мы немного перепрыгнем через файлы, перечисленные выше.

В CustomerGateway.cs добавьте следующий блок кода:

    /// <summary>
    /// Adds a bank account profile to the user and returns the profile ID
    /// </summary>
    /// <returns></returns>
    public string AddBankAccount(string profileID, string nameOnAccount, string accountNumber, string routingNumber)
    {
        var req = new createCustomerPaymentProfileRequest();
        req.customerProfileId = profileID;
        req.paymentProfile = new customerPaymentProfileType();
        req.paymentProfile.payment = new paymentType();

        bankAccountType new_bank = new bankAccountType();
        new_bank.nameOnAccount = nameOnAccount;
        new_bank.accountNumber = accountNumber;
        new_bank.routingNumber = routingNumber;

        req.paymentProfile.payment.Item = new_bank;

        var response = (createCustomerPaymentProfileResponse)_gateway.Send(req);

        return response.customerPaymentProfileId;
    }

В PaymentProfile.cs добавить некоторые общедоступные свойства

    public string BankNameOnAccount {get; set; }
    public string BankAccountNumber { get; set; }
    public string BankRoutingNumber { get; set; }

Измените следующий блок конструктора PaymentProfile(customerPaymentProfileMaskedType apiType):

        if (apiType.payment != null) {
            if(apiType.payment.Item is bankAccountMaskedType) {
                var bankAccount = (bankAccountMaskedType)apiType.payment.Item;
                this.BankNameOnAccount = bankAccount.nameOnAccount;
                this.BankAccountNumber = bankAccount.accountNumber;
                this.BankRoutingNumber = bankAccount.routingNumber;
            }
            else if (apiType.payment.Item is creditCardMaskedType)
            {
                var card = (creditCardMaskedType)apiType.payment.Item;
                this.CardType = card.cardType;
                this.CardNumber = card.cardNumber;
                this.CardExpiration = card.expirationDate;
            }
        }

Добавьте этот блок к методу PaymentProfile.ToAPI():

        if (!string.IsNullOrEmpty(this.BankAccountNumber))
        {
            bankAccountType new_bank = new bankAccountType();
            new_bank.nameOnAccount = BankNameOnAccount;
            new_bank.accountNumber = BankAccountNumber;
            new_bank.routingNumber = BankRoutingNumber;

            result.payment.Item = new_bank;
        }

Добавьте в общедоступные свойства SubscriptionRequest.cs > SubscriptionRequest (вокруг строки 187)

    public string BankNameOnAccount {get; set; }
    public string BankAccountNumber { get; set; }
    public string BankRoutingNumber { get; set; }

Добавьте следующее else, если block TWICE в SubscriptionRequest. Первый раз в методе ToAPI, второй - в методе ToUpdateableAPI, в обоих случаях он идет после нулевой проверки номера CC.

        else if (!String.IsNullOrEmpty(this.BankAccountNumber))
        {
            bankAccountType new_bank = new bankAccountType();
            new_bank.nameOnAccount = BankNameOnAccount;
            new_bank.accountNumber = BankAccountNumber;
            new_bank.routingNumber = BankRoutingNumber;

            sub.payment = new paymentType();
            sub.payment.Item = new_bank;
        }

Добавьте в Transaction.cs следующие общедоступные свойства

    public string BankNameOnAccount { get; set; }
    public string BankAccountNumber { get; set; }
    public string BankRoutingNumber { get; set; }

В Transaction.cs в статическом методе NewFromResponse (transactionDetailsType trans) найдите блок, который проверяет trans.payment != null и настраивает, как показано:

        if (trans.payment != null) {
            if (trans.payment.Item.GetType() == typeof(creditCardMaskedType))
            {
                var cc = (creditCardMaskedType)trans.payment.Item;
                result.CardNumber = cc.cardNumber;
                result.CardExpiration = cc.expirationDate;
                result.CardType = cc.cardType;
            } 
            else if (trans.payment.Item.GetType() == typeof(bankAccountMaskedType))
            {
                var bankAccount = (bankAccountMaskedType)trans.payment.Item;
                result.BankNameOnAccount = bankAccount.nameOnAccount;
                result.BankAccountNumber = bankAccount.accountNumber;
                result.BankRoutingNumber = bankAccount.routingNumber;
            }
        }