Песочница Paypal Оплата заказа с использованием сохраненной карты Vault - PullRequest
1 голос
/ 18 февраля 2020

Я использую Vault для хранения информации о кредитной карте в учетной записи песочницы Paypal.

Теперь я хочу интегрировать процесс оплаты, используя сохраненный идентификатор кредитной карты. пожалуйста, руководство, как достичь этого. Ниже приведен блок кода.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // 
        PaypalCCModel ccmodel = new PaypalCCModel();
        ccmodel.Number = "5555555555554444";  //"4111111111111111"; //"4012888888881881";// "4417119669820331"; // Visa
        ccmodel.ExpireMonth = "11";
        ccmodel.ExpireYear = "2021";
        //ccmodel.cvv2 = "222";
        ccmodel.Type = "MasterCard";

        PaymentViaStoredCard(StoreCreditCardInPaypal(ccmodel));
        return View();
    }

    // It return Vault Credit Card Id 
    private string StoreCreditCardInPaypal(PaypalCCModel ccmodel)
    {
        Address billingAddress = new Address();
        billingAddress.city = "Johnstown";
        billingAddress.country_code = "US";
        billingAddress.line1 = "52 N Main ST";
        billingAddress.postal_code = "43210";
        billingAddress.state = "OH";

        //Creating the CreditCard Object and assigning values
        CreditCard credtCard = new CreditCard();
        credtCard.expire_month = int.Parse(ccmodel.ExpireMonth);
        credtCard.expire_year = int.Parse(ccmodel.ExpireYear);
        credtCard.number = ccmodel.Number;
        credtCard.type = ccmodel.Type.ToLower();
        //credtCard.cvv2 = ccmodel.cvv2;
        credtCard.first_name = "pankaj";
        credtCard.last_name = "Kumar";
        credtCard.billing_address = billingAddress;

        try
        {
            //Getting the API Context to authenticate the call to Paypal Server
            PayPal.Api.APIContext apiContext = Configuration.GetAPIContext();
            Dictionary<string, string> headers = new Dictionary<string, string>();
            //headers.Add("Content-Type", "application/json");
            //headers.Add("Authorization", "Bearer "+ apiContext.AccessToken.ToString());
            apiContext.HTTPHeaders = headers;
            // Storing the Credit Card Info in the PayPal Vault Server
            CreditCard createdCreditCard = credtCard.Create(apiContext);

            //Saving the User's Credit Card ID returned by the PayPal
            //You can use this ID for future payments via User's Credit Card
            //SaveCardID(User.Identity.Name, createdCreditCard.id);
            return createdCreditCard.id;
        }
        catch (PayPal.PayPalException ex)
        {
            //Logger.LogError("Error: " + ex.Message);
            return "-1";
        }
        catch (Exception ex)
        {
            //Logger.LogError("Error: " + ex.Message);
        }

        return "-1";
    }

    public void PaymentViaStoredCard(string CardID)
    {
        // Preparing Item
        Item item = new Item();
        item.name = "Item Name";
        item.currency = "USD";
        item.price = "1";
        item.quantity = "1";
        item.sku = "sku-1123324";

        List<Item> itms = new List<Item>();
        itms.Add(item);
        ItemList itemList = new ItemList();
        itemList.items = itms;

        //Here is the Credit Card detail which we need to use from our database
        CreditCardToken credCardToken = new CreditCardToken();
        //Here, we are assigning the User's Credit Card ID which we saved in Database
        credCardToken.credit_card_id = CardID;

        //Specify Payment Details
        Details details = new Details();
        details.shipping = "1";
        details.subtotal = "1";
        details.tax = "1";

        //Specify the Total Amount
        Amount amnt = new Amount();
        amnt.currency = "USD";
        // Total must be equal to the sum of shipping, tax and subtotal.
        amnt.total = "3";
        amnt.details = details;

        //Create Transaction Object
        Transaction tran = new Transaction();
        tran.amount = amnt;
        tran.description = "This is the recurring payment transaction";
        tran.item_list = itemList;

        //Adding the transaction above to the list
        List<Transaction> transactions = new List<Transaction>();
        transactions.Add(tran);

        //Specifying the funding Instrument here.
        //Notice that we are not using any credit card details here
        //But we are using the Credit Card Object which has the Card ID
        FundingInstrument fundInstrument = new FundingInstrument();
        fundInstrument.credit_card_token = credCardToken;

        //Adding the Funding Instrument to the list
        List<FundingInstrument> fundingInstrumentList = new List<FundingInstrument>();
        fundingInstrumentList.Add(fundInstrument);

        //Specify the fundind Instrument List and Payment Method as Credit Card
        //Because we are making the payment using the store Credit Card
        Payer payr = new Payer();
        payr.funding_instruments = fundingInstrumentList;
        payr.payment_method = "credit_card";

        //Finally Making payment Object and filling it with values
        Payment pymnt = new Payment();
        pymnt.intent = "sale";
        pymnt.payer = payr;
        pymnt.transactions = transactions;

        try
        {
            //Getting the API Context to authenticate the Call to Paypal Server
            PayPal.Api.APIContext apiContext = Configuration.GetAPIContext();

            // Making the payment using a valid APIContext
            Payment createdPayment = pymnt.Create(apiContext);
        }
        catch (PayPal.PayPalException ex)
        {
            //Logger.LogError("Error: " + ex.Message);
        }
    }
}

Метод PaymentViaStoredCard хранит информацию о кредитной карте в хранилище песочницы PayPal и идентификатор карты хранилища возврата, который передается методу PaymentViaStoredCard для оплаты суммы PayPal. Но я получаю ошибку в методе PaymentViaStoredCard, например внутреннюю ошибку сервера. Полное описание ошибки: {"name": "INTERNAL_SERVICE_ERROR", "message": "Произошла внутренняя ошибка службы.", "Information_link": "developer.paypal.com/docs/api/payments/…"}

...