在调用SetExpressCheckout方法时,我没有将Object Reference设置为对象的实例

时间:2016-04-15 12:40:49

标签: c# asp.net paypal

我长期以来一直面临这个问题,我真的需要帮助。我正在尝试调用Paypal SetExpressCheckout方法。但是我在第一行得到了错误。我检查了所有必填字段,我确信我没有在必填字段中传递任何空值。我有一个Paypal开发者帐户,我正在使用其API凭据。

[//包含签名凭据和其他所需配置的配置映射。             //有关配置参数的完整列表,请参阅Wiki页面             // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]

        // Create the PayPalAPIInterfaceServiceService service object to make the API call
        PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

        SetExpressCheckoutRequestType setExpressCheckoutReq = new SetExpressCheckoutRequestType();
        SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType();


        // (Optional) Email address of the buyer as entered during checkout.
        // PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages.
        // Character length and limitations: 127 single-byte alphanumeric characters            
        details.BuyerEmail = buyerEmail;
        details.ReturnURL = returnUrl;
        details.CancelURL = cancelUrl;

        // Fix for release
        // NOTE: Setting this field overrides the setting you specified in your Merchant Account Profile
        // Indicates whether or not you require the buyer's shipping address on 
        // file with PayPal be a confirmed address. For digital goods, 
        // this field is required, and you must set it to 0. It is one of the following values:
        //  0 – You do not require the buyer's shipping address be a confirmed address.
        //  1 – You require the buyer's shipping address be a confirmed address.
        //  Note:
        //  Setting this field overrides the setting you specified in your Merchant Account Profile.
        //  Character length and limitations: 1 single-byte numeric character

        details.ReqConfirmShipping = ReqConfirmShipping;

        // (Optional) Determines whether or not the PayPal pages should 
        //display the shipping address set by you in this SetExpressCheckout request,
        // not the shipping address on file with PayPal for this buyer. Displaying 
        // the PayPal street address on file does not allow the buyer to edit that address. 
        // It is one of the following values:
        //  0 – The PayPal pages should not display the shipping address.
        //  1 – The PayPal pages should display the shipping address.
        // Character length and limitations: 1 single-byte numeric character
        details.AddressOverride = addressoverride;
        details.NoShipping = noShipping;


        decimal itemTotal = 0.0M;
        decimal orderTotal = 0.0M;

        // Cost of item. This field is required when you pass a value for ItemCategory.
        //Split by |
        string amountItems = itemAmounts;

        // Item quantity. This field is required when you pass a value for ItemCategory. 
        // For digital goods (ItemCategory=Digital), this field is required.
        // Character length and limitations: Any positive integer             
        //Split by |
        string qtyItems = itemQuantities;

        // Item name. This field is required when you pass a value for ItemCategory.                   
        //Split by |
        string names = itemNames;

        List<PaymentDetailsItemType> lineItems = new List<PaymentDetailsItemType>();
        if (itemNames.Contains('|'))
        {
            string[] INames = itemNames.Split('|');
            string[] IQtys = itemQuantities.Split('|');
            string[] IAmts = itemAmounts.Split('|');

            for (int i = 0; i < INames.Length; i++)
            {
                PaymentDetailsItemType item = new PaymentDetailsItemType();
                BasicAmountType amt = new BasicAmountType();

                // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. 
                amt.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
                amt.value = IAmts[i];
                item.Quantity = Convert.ToInt32(Convert.ToDecimal(IQtys[i]));
                item.Name = INames[i];
                item.Amount = amt;


                // Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values:
                // 1. Digital
                // 2. Physical  
                // By default its Physical for us
                item.ItemCategory = ItemCategoryType.PHYSICAL;
                itemTotal += Convert.ToDecimal(IQtys[i]) * Convert.ToDecimal(IAmts[i]);
                lineItems.Add(item);
            }
        }
        else
        {
            PaymentDetailsItemType item = new PaymentDetailsItemType();
            BasicAmountType amt = new BasicAmountType();

            // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. 
            amt.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
            amt.value = itemAmounts;
            item.Quantity = Convert.ToInt32(Convert.ToDecimal(itemQuantities));
            item.Name = itemNames;
            item.Amount = amt;


            // Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values:
            // 1. Digital
            // 2. Physical  
            // By default its Physical for us
            item.ItemCategory = ItemCategoryType.PHYSICAL;
            itemTotal += Convert.ToDecimal(itemQuantities) * Convert.ToDecimal(itemAmounts);
            lineItems.Add(item);
        }


        // (Optional) Item sales tax.
        // Note: You must set the currencyID attribute to one of 
        // the 3-character currency codes for any of the supported PayPal currencies.
        // Character length and limitations: Value is a positive number which cannot exceed $10,000 USD in any currency.
        // It includes no currency symbol. It must have 2 decimal places, the decimal separator must be a period (.), 
        // and the optional thousands separator must be a comma (,).
        //if (salesTax != string.Empty)
        //{
        //    item.Tax = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["salesTax"]);
        //}

        orderTotal += itemTotal;

        List<PaymentDetailsType> payDetails = new List<PaymentDetailsType>();
        PaymentDetailsType paydtl = new PaymentDetailsType();

        // How you want to obtain payment. When implementing parallel payments, 
        // this field is required and must be set to Order.
        // When implementing digital goods, this field is required and must be set to Sale.
        // If the transaction does not include a one-time purchase, this field is ignored.
        // It is one of the following values:
        // Sale – This is a final sale for which you are requesting payment (default).
        // Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
        // Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture.
        // BY DEFAULT THIS IS SALE
        paydtl.PaymentAction = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), paymentType);

        // (Optional) Total shipping costs for this order.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency codes 
        // for any of the supported PayPal currencies.
        // Character length and limitations: 
        // Value is a positive number which cannot exceed $10,000 USD in any currency.
        // It includes no currency symbol. 
        // It must have 2 decimal places, the decimal separator must be a period (.), 
        // and the optional thousands separator must be a comma (,)
        if (shipTotal != string.Empty)
        {
            BasicAmountType shippingTotal = new BasicAmountType();
            shippingTotal.value = shipTotal.Trim();
            shippingTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
            orderTotal += Convert.ToDecimal(shipTotal.Trim());
            paydtl.ShippingTotal = shippingTotal;
        }

        // (Optional) Total shipping insurance costs for this order. 
        // The value must be a non-negative currency amount or null if you offer insurance options.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency 
        // codes for any of the supported PayPal currencies.
        // Character length and limitations: 
        // Value is a positive number which cannot exceed $10,000 USD in any currency. 
        // It includes no currency symbol. It must have 2 decimal places,
        // the decimal separator must be a period (.), 
        // and the optional thousands separator must be a comma (,).
        // InsuranceTotal is available since version 53.0.

        //if (parameters["insuranceTotal"] != string.Empty)
        //{
        //    paydtl.InsuranceTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["insuranceTotal"]);
        //    paydtl.InsuranceOptionOffered = "true";
        //    orderTotal += Convert.ToDecimal(parameters["insuranceTotal"]);
        //}

        // (Optional) Total handling costs for this order.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency codes 
        // for any of the supported PayPal currencies.
        // Character length and limitations: Value is a positive number which 
        // cannot exceed $10,000 USD in any currency.
        // It includes no currency symbol. It must have 2 decimal places, 
        // the decimal separator must be a period (.), and the optional 
        // thousands separator must be a comma (,). 

        //if (parameters["handlingTotal"] != string.Empty)
        //{
        //    paydtl.HandlingTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["handlingTotal"]);
        //    orderTotal += Convert.ToDecimal(parameters["handlingTotal"]);
        //}

        // (Optional) Sum of tax for all items in this order.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency codes
        // for any of the supported PayPal currencies.
        // Character length and limitations: Value is a positive number which 
        // cannot exceed $10,000 USD in any currency. It includes no currency symbol.
        // It must have 2 decimal places, the decimal separator must be a period (.),
        // and the optional thousands separator must be a comma (,).
        if (salesTax != string.Empty)
        {
            paydtl.TaxTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode), salesTax);
            orderTotal += Convert.ToDecimal(salesTax);
        }

        // (Optional) Description of items the buyer is purchasing.
        // Note:
        // The value you specify is available only if the transaction includes a purchase.
        // This field is ignored if you set up a billing agreement for a recurring payment 
        // that is not immediately charged.
        // Character length and limitations: 127 single-byte alphanumeric characters
        //if (parameters["orderDescription"] != string.Empty)
        //{
        //    paydtl.OrderDescription = parameters["orderDescription"];
        //}

        BasicAmountType itemsTotal = new BasicAmountType();
        itemsTotal.value = Convert.ToString(itemTotal);

        // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables. 
        itemsTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);

        paydtl.OrderTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode), Convert.ToString(orderTotal));
        paydtl.PaymentDetailsItem = lineItems;

        paydtl.ItemTotal = itemsTotal;

        #region shipping address

        AddressType shippingAddress = new AddressType();
        shippingAddress.Street1 = shipStreet;
        shippingAddress.CityName = shipCity;
        shippingAddress.StateOrProvince = shipState;
        shippingAddress.Country = CountryCodeType.US;
        shippingAddress.PostalCode = shipPostalcode;
        shippingAddress.Name = shipName;
        paydtl.ShipToAddress = shippingAddress;
        #endregion



        details.PaymentDetails.Add(paydtl);

        setExpressCheckoutReq.SetExpressCheckoutRequestDetails = details;
        SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq();
        expressCheckoutReq.SetExpressCheckoutRequest = setExpressCheckoutReq;

        SetExpressCheckoutResponseType response = null;
        try
        {

            response = service.SetExpressCheckout(expressCheckoutReq);
        }
        catch (System.Exception ex)
        {
            //contextHttp.Response.Write(ex.Message);
            return null;
        }

        Dictionary<string, string> responseValues = new Dictionary<string, string>();
        responseValues.Add("Acknowledgement", response.Ack.ToString().Trim().ToUpper());
        if (response.Ack.ToString().Trim().ToUpper() == "SUCCESS")
        {
            responseValues.Add("Token", response.Token.ToString().Trim());
            responseValues.Add("TimeStamp", response.Timestamp.ToString().Trim());
        }
        return responseValues;

    }][1]

我还附上了我得到的错误的屏幕截图。我使用的是1.3.5版本的PaypalCoreSDK。任何帮助都会非常感激。

例外:

PayPal.APIService.MakeRequestUsing(IAPICallPreHandler apiCallHandler) 
at PayPal.BasePayPalService.Call(IAPICallPreHandler apiCallHandler)
at PayPal.PayPalAPIInterfaceService.PayPalAPIInterfaceServiceService.SetExpressChec‌​kout(SetExpressCheckoutReq setExpressCheckoutReq, String apiUserName) 
at PayPal.PayPalAPIInterfaceService.PayPalAPIInterfaceServiceService.SetExpressChec‌​kout(SetExpressCheckoutReq setExpressCheckoutReq)      upvote
at gs_PayPalECAPI.PayPalProcess.SetExpressCheckout_Ecommerce(Dictionary`2 configurationMap, String returnUrl, String cancelUrl, String currencyCode, String paymentType, String ReqConfirmShipping, String addressoverride, String noShipping, String buyerEmail, String itemAmounts, String itemQuantities, String itemNames, String salesTax, String shipTotal, String shipStreet, String shipState, String shipCity, String shipPostalcode, String shipName) 

1 个答案:

答案 0 :(得分:0)

最后得到了一个解决方案和代码工作。没有任何东西被传递为null,但是有些东西缺失,我不知道必须要做。

首先,在实施时,应该使用.Net Framework 4.5或更高版本。 其次,必须在调用SetExpressCheckout方法之前设置以下内容:

System.Net.ServicePointManager.Expect100Continue = true;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
System.Net.ServicePointManager.DefaultConnectionLimit = 9999;