5006 : Не удалось перенаправить на веб-сайт поставщика. SagePay

Привет, я использую интеграцию с сервером SagePay после процесса оплаты.

5006 : Не удалось перенаправить на веб-сайт поставщика. Поставщику не удалось предоставить RedirectionURL.

мой файл веб-конфигурации:

<sagePay>
  <!-- The public-facing hostname that SagePay can use to contact the site -->

    <add key="NotificationHostName" value="ubtfront.azurewebsites.net" />
  <!--<add key="NotificationHostName" value="ubtfront.azurewebsites.net" />-->
  <!-- The protocol defaults to http, but you can override that to https with the following setting -->
   <add key="Protocol" value="http" /> 
  <!-- Your notification controller -->
  <add key="NotificationController" value="PaymentResponse" />
  <!-- Your notification action. These three settings together are used to build the notification URL -->
  <!-- EG: http://my.external.hostname/PaymentResponse/Notify -->
  <add key="NotificationAction" value="Notify" />
  <!-- Action names for URLS that the user will be directed to after payment either succeeds or fails -->
  <!-- The URL is constructed from the notificationHostName and NotificationController. -->
  <!-- Eg: http://my.external.hostname/PaymentResponse/Success -->
  <add key="SuccessAction" value="Success" />
  <add key="FailedAction" value="Failed" />

  <!-- VAT multiplier. Currently at 20% -->
  <add key="VatMultiplier" value="1" />
  <!-- Name of vendor. You will need to change this -->
  <add key="VendorName" value="VendorName" />
  <!-- Simulator, Test or Live -->
  <add key="Mode" value="Test" />
</sagePay>

Мой контроллер ответа на платеж:

 public class PaymentResponseController : Controller
    {
        IOrderRepository _orderRepository;

        public PaymentResponseController(IOrderRepository orderRepository)
        {
            _orderRepository = orderRepository;
        }

        public ActionResult Notify(SagePayResponse response)
        {
            // SagePay should have sent back the order ID
            if (string.IsNullOrEmpty(response.VendorTxCode))
            {
                return new ErrorResult();
            }

            // Get the order out of our "database"
            var order = _orderRepository.GetById(response.VendorTxCode);

            // IF there was no matching order, send a TransactionNotfound error
            if (order == null)
            {
                return new TransactionNotFoundResult(response.VendorTxCode);
            }

            // Check if the signature is valid.
            // Note that we need to look up the vendor name from our configuration.
            if (!response.IsSignatureValid(order.SecurityKey, SagePayMvc.Configuration.Current.VendorName))
            {
                return new InvalidSignatureResult(response.VendorTxCode);
            }

            // All good - tell SagePay it's safe to charge the customer.
            return new ValidOrderResult(order.VendorTxCode, response);
        }

        public ActionResult Failed(string vendorTxCode)
        {
            return View();
        }

        public ActionResult Success(string vendorTxCode)
        {
            return View();
        }
    }

Я не могу понять, где я ошибаюсь, пожалуйста, помогите мне понять это. Любая помощь приветствуется....


person kirushan    schedule 26.07.2016    source источник
comment
вы должны передать URL-адрес успеха и неудачный URL-адрес в свой запрос sagepay.   -  person Sunil Kumar    schedule 26.07.2016
comment
Не могли бы вы прислать мне образец запроса. Я потерян с этим. Помогите пожалуйста мне. @СунилКумар   -  person kirushan    schedule 26.07.2016
comment
Вы случайно не используете пакет SagePayMvc Nuget?   -  person Diego    schedule 31.07.2016
comment
да.. Удалось ли вам это сделать? @Диего   -  person kirushan    schedule 02.08.2016
comment
Да, отправил ответ, надеюсь, он укажет вам правильное направление. @кирушан   -  person Diego    schedule 02.08.2016


Ответы (2)


Пожалуйста, обратитесь к следующему коду, вы должны передать свой успех и неудачу URL с вашим request, я добился этого, используя следующий код:

       private static void SetSagePayFormAPIData(IFormPayment request, PaymentGatewayRequest paymentRequest)
        {
            var isCollectRecipientDetails = SagePaySettings.IsCollectRecipientDetails;

            request.VpsProtocol = SagePaySettings.ProtocolVersion;
            request.TransactionType = SagePaySettings.DefaultTransactionType;
            request.Vendor = SagePaySettings.VendorName;

            //Assign Vendor tx Code.
            request.VendorTxCode = SagePayFormIntegration.GetNewVendorTxCode();

            request.Amount = paymentRequest.GrossAmount;
            request.Currency = SagePaySettings.Currency;
            request.Description = "Your Payment Description";              
            request.SuccessUrl = "Your SuccessUrl";
            request.FailureUrl = "Your FailureUrl"; 
            request.BillingSurname = paymentRequest.BillingSurname;
            request.BillingFirstnames = paymentRequest.BillingFirstnames;
            request.BillingAddress1 = paymentRequest.BillingAddress1;
            request.BillingCity = paymentRequest.BillingCity;//Pass Billing City Name
            request.BillingCountry = paymentRequest.BillingCountry;//Pass Billing City Name

            request.DeliverySurname = paymentRequest.DeliverySurname;
            request.DeliveryFirstnames = paymentRequest.DeliveryFirstnames;
            request.DeliveryAddress1 = paymentRequest.DeliveryAddress1;
            request.DeliveryCity = paymentRequest.DeliveryCity;//Pass Delivery City Name
            request.DeliveryCountry = paymentRequest.DeliveryCountry;//Pass Delivery Country

            //Optional
            request.CustomerName = paymentRequest.BillingFirstnames + " " + paymentRequest.BillingSurname;
            request.VendorEmail = SagePaySettings.VendorEmail;
            request.SendEmail = SagePaySettings.SendEmail;

            request.EmailMessage = SagePaySettings.EmailMessage;
            request.BillingAddress2 = paymentRequest.BillingAddress2;
            request.BillingPostCode = paymentRequest.BillingPostCode;
            request.BillingState = "UK";//Pass Billing State
            request.BillingPhone = paymentRequest.BillingPhone;
            request.DeliveryAddress2 = paymentRequest.DeliveryAddress2;
            request.DeliveryPostCode = paymentRequest.DeliveryPostCode; //Delivery Post Code
            request.DeliveryState = "UK"; //Pass Delivery State
            request.DeliveryPhone = paymentRequest.DeliveryPhone;

            request.AllowGiftAid = SagePaySettings.AllowGiftAid;
            request.ApplyAvsCv2 = SagePaySettings.ApplyAvsCv2;
            request.Apply3dSecure = SagePaySettings.Apply3dSecure;

            request.CustomerEmail = paymentRequest.CustomerEmail;

            request.BillingAgreement = "";
            request.ReferrerId = SagePaySettings.ReferrerID;

            request.BasketXml = SagePayPaymentController.ToBasketstring(paymentRequest);

            request.VendorData = string.Empty; //Use this to pass any data you wish to be displayed against the transaction in My Sage Pay.

        }

Надеюсь, это поможет вам :)

person Sunil Kumar    schedule 26.07.2016
comment
В интеграции типа сервера вы должны пройти Notification URL Вот так: NotificationUrl = ServerPaymentRequest.NotificationUrl; - person Sunil Kumar; 02.08.2016

Sage не любит порты на URL-адресах (из документации Sage):

Серверы Sage Pay отправляют HTTP или HTTPS POST в сценарий NotificationURL на вашем сервере, чтобы указать результат транзакции с использованием портов 80 и 443. Пожалуйста, убедитесь, что вы используете только эти порты, так как жесткое кодирование любых других портов будет генерировать ошибки.

Библиотека SagePayMvc использует текущий контекст для создания URL-адресов Notify, Success и Failure, что означает, что она также добавляет текущий порт запроса.

При локальном тестировании я ожидал, что мой промежуточный сервер (Azure) получит ответ от Sage, но мой текущий порт добавлялся к запросу, http://example.com:51118/PaymentResponse/Notify в результате чего Sage выдавал ошибку 5006.

Я использую MVC5, поэтому мне пришлось настроить части кода в библиотеке, чтобы заставить его работать.

Я изменил свойство BuildNotificationUrl в классе DefaultUrlResolver, чтобы создать URL-адрес без использования порта, поскольку по умолчанию он должен быть 80 или 443.

Вы можете сделать что-то более менее похожее на это:

public virtual string BuildNotificationUrl(RequestContext context) {
    var configuration = Configuration.Current;
    var urlHelper = new UrlHelper(context);
    var routeValues = new RouteValueDictionary(new {controller = configuration.NotificationController, action = configuration.NotificationAction});
    var url = urlHelper.RouteUrl(null, routeValues, configuration.Protocol, configuration.NotificationHostName);
    var uri = new Uri(url);

    return uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped);
}

Надеюсь это поможет.

person Diego    schedule 02.08.2016