SagePay商家会话密钥 - AJAX

时间:2017-09-06 10:51:21

标签: jquery ajax sagepay

我们正试图在一些JQuery代码中使用AJAX调用与SagePay API集成。此特定API提供了一个JSON响应,如下所示:

{
"expiry": "2017-09-06T11:20:25.820+01:00",
"merchantSessionKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

使用以下代码,我们可以成功对API进行身份验证,但随后会收到有关Access-Control-Allow-Origin的消息。

XMLHttpRequest无法加载https://pi-test.sagepay.com/api/v1/merchant-session-keys。对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin标头。因此,不允许原始null访问。

之前有没有人遇到过这个问题?

var myAPI = "https://pi-test.sagepay.com/api/v1/merchant-session-keys";
    var myKey = "xxx";
    var myPassword = "xxx";
    var myTokenId = "xxx";

    $.ajax({
        url: myAPI,
        headers: {
            'content-Type': 'application/json',
            'username': myKey,
            'password': myPassword,
            'authorization': 'Basic ' + myTokenId
        },
        method: 'POST',
        dataType: 'json',
        data: {
            'vendorName':'xxx'
        },
        success: function(data){
            console.log(data.merchantSessionKey);
            console.log(data.expiry);
        },
        error: function () {
            console.log('MSK unsuccessful');
        }
      });

1 个答案:

答案 0 :(得分:2)

您不应该直接使用jquery ajax向SagePay发出POST请求。相反,您必须向服务器发出ajax请求,然后将数据发布到SagePay。您可以在此处获取php示例:SagePay drop-in Checkout

请检查我以前使用的c#代码。

HTML:

<div id="sagePayDetails"></div>
<form id="paymentForm"><input type="submit" value="Submit"></input></form>

jquery的:

$.ajax({
url: "@Url.Content("~/YourServerMethod")",
type: "GET",
success: function (data) {
    if (data.Status == "SUCCESS") {
        sagepayCheckout(
        { 
            merchantSessionKey: data.SessionKey,
            containerSelector: "#sagePayDetails" 
        }).form({ formSelector: "#paymentForm" });
    } else {
        showError("Some error occurred, please try again later.");
    }
},
error: function (xhr, status, error) {
    showError("Some error occurred, please try again later.");
}});

C#:

public JsonResult YourServerMethod(){
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
        SecurityProtocolType.Tls11 |
        SecurityProtocolType.Tls12;

var invokeUrl = "https://pi-test.sagepay.com/api/v1/merchant-session-keys";
var integrationKey = "*****"
var integrationPassword = "*****";
var paymentVendor = "YourVendorName";
var apiKey = Base64Encode(
    integrationKey + ":" + integrationPassword); //Your method to encode string to Base64

var request = new SagePayEntity.MerchantSessionKeyRequest {
    vendorName = paymentVendor };
var requestData = new StringContent(
 JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");

var handler = new WebRequestHandler();
handler.ClientCertificates.Add(new X509Certificate2(
    Server.MapPath("~/Certificate.crt"))); //Your SSL certificate for the domain
handler.CachePolicy = new HttpRequestCachePolicy(
    HttpRequestCacheLevel.NoCacheNoStore);

var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Basic", apiKey);
client.DefaultRequestHeaders
    .Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync(invokeUrl, requestData).Result;
var result = response.Content.ReadAsStringAsync().Result;

if (response.StatusCode == HttpStatusCode.Created)
{
    var sageResponse = JsonConvert
        .DeserializeObject<SagePayEntity.MerchantSessionKeyResponse>(result,
        new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None
        });
    return Json(new { SessionKey = sageResponse.MerchantSessionKey,
        Status = "SUCCESS" },
        JsonRequestBehavior.AllowGet);
}
else
{
    return Json(new { Status = "FAILURE" });
}}