Skip to content

Instantly share code, notes, and snippets.

@MarkNijhof
Created February 15, 2020 19:14
Show Gist options
  • Save MarkNijhof/8272b41156a4c0c80aa5405dd148a1d6 to your computer and use it in GitHub Desktop.
Save MarkNijhof/8272b41156a4c0c80aa5405dd148a1d6 to your computer and use it in GitHub Desktop.
var get_payment_methods = function() {
var callback = function(httpRequest) {
if (httpRequest.readyState === 4) {
if (httpRequest.status >= 200 && httpRequest.status < 300) {
var response = JSON.parse(httpRequest.response);
<%= if afterpay_enabled do %>
// To make sure this only happens in Norway and Sweden
// I want to have the Afterpay method below Klarna Slice It
// or Pay Later or if neither is there on top.
var index = response.paymentMethods.findIndex(function(x) {
return x.type === "klarna_account";
});
if (index === -1) {
index = response.paymentMethods.findIndex(function(x) {
return x.type === "klarna";
});
}
if (index !== -1) {
index = index+1;
} else {
index = 0;
}
// Insert the new payment method inside the payment
// methods array in the correct place. I am using the
// existing afterpay_account type because I didn't
// want to look at styling again
response.paymentMethods.splice(index, 0, {
name: "Afterpay Invoice",
type: "afterpay_default",
details: [{
type: "fieldSet",
key: "personalDetails",
details: [{
type: "tel",
key: "socialSecurityNumber"
}]
},{
type: "boolean",
key: "consentCheckbox"
}]
});
<% end %>
create_drop_in(response);
} else {
var response = JSON.parse(httpRequest.response);
console.error(httpRequest.status, response);
}
}
};
get("/adyen/get_payment_methods", callback);
};
var create_drop_in = function(paymentMethodsResponse) {
const configuration = {
locale: "NO",
countryCode: "<%= String.upcase(get_country_code(country)) %>",
environment: "live",
openFirstPaymentMethod: false,
paymentMethodsResponse: paymentMethodsResponse
};
const checkout = new AdyenCheckout(configuration);
const dropin = checkout
.create('dropin', {
amount: <%= total_amount %>,
currencyCode: '<%= currency %>',
countryCode: "<%= String.upcase(get_country_code(country)) %>",
paymentMethodsConfiguration: {
card: {
hasHolderName: true,
holderNameRequired: true,
enableStoreDetails: false,
hideCVC: false,
name: 'Credit or debit card',
holderName: "<%= first_name %> <%= last_name %>"
},
ideal: {
showImage: true
}
},
onSubmit: function(state, dropin) {
<%= if afterpay_enabled do %>
// Only add this when we are in Norway or Sweden,
// if we would be in Netherlands or Belgium we might
// have an afterpay session via Adyen
if (state.data.paymentMethod.type === "afterpay_default") {
var data = {
user_id: "<%= @context.user.id %>",
ssn: state.data.paymentMethod.personalDetails.socialSecurityNumber
};
var callback = function(httpRequest) {
if (httpRequest.readyState === 4) {
if (httpRequest.status >= 200 && httpRequest.status < 300) {
var response = JSON.parse(httpRequest.response);
dropin.setStatus('success', { message: 'Yay! Betalingen var vellykket!' });
track_purchase();
} else {
var response = JSON.parse(httpRequest.response);
var errors = response.riskCheckMessages || response.errors || [];
var first = errors.find((r) => typeof r.type !== "undefined" && r.type === "BusinessError")
if (typeof first !== "undefined") {
// Afterpay doesn't like re-using order numbers so...
// Handle the error after that.
re_create_order(first.message);
} else {
re_create_order("error");
}
}
}
};
post("/order/authorize", data, callback);
return;
}
<% end %>
// handle the Adyen errors
var callback = function(httpRequest) {
if (httpRequest.readyState === 4) {
if (httpRequest.status >= 200 && httpRequest.status < 300) {
var response = JSON.parse(httpRequest.response);
handle_dropin_response(response, dropin);
} else if (httpRequest.status >= 400 && httpRequest.status < 500) {
var response = JSON.parse(httpRequest.response);
show_error(response.message);
} else {
show_error('Something went wrong.');
console.error(httpRequest.status, response);
}
}
};
post("/adyen/payments", state, callback);
},
onAdditionalDetails: function(state, dropin) {
var callback = function(httpRequest) {
if (httpRequest.readyState === 4) {
if (httpRequest.status >= 200 && httpRequest.status < 300) {
var response = JSON.parse(httpRequest.response);
handle_dropin_response(response, dropin);
} else if (httpRequest.status >= 400 && httpRequest.status < 500) {
var response = JSON.parse(httpRequest.response);
show_error(response.message);
} else {
show_error('Something went wrong.');
console.error(httpRequest.status, response);
}
}
};
post("/adyen/payment_details", state, callback);
},
onSelect: function(dropin) {
document.getElementById("scroll_top").scrollIntoView();
<%= if afterpay_enabled do %>
// Add some field restrictions and update the terms link
setTimeout(function() {
var nodes = document.getElementsByClassName("adyen-checkout__payment-method--afterpay_default");
var afterpay = nodes.length > 0 ? nodes[0] : undefined;
if (afterpay) {
var ssn = afterpay.querySelector('input[name=personalDetails__socialSecurityNumber]');
ssn.setAttribute("placeholder", "<%= ssn_format %>");
ssn.setAttribute("size", "<%= ssn_size %>");
ssn.setAttribute("maxlength", "<%= ssn_size %>");
ssn.setAttribute("pattern", "[0-9.]+");
var link = afterpay.querySelector('a');
link.href = "<%= credit_terms_link %>";
}
}, 100);
<% end %>
},
onReady: function() {
<%= if back_from_redirect do %>
document.getElementById("scroll_top").scrollIntoView();
<%= unless is_nil(Map.get(@context.params, :result_code)) do %>
var result_code = "<%= String.downcase(Map.get(@context.params, :result_code)) %>";
switch (result_code) {
case "authorised":
dropin.setStatus('success', { message: 'Yay! Betalingen var vellykket!' });
track_purchase(result_code);
send_error("ORDER: /flow/order/payment:onReady", result_code, "<%= @context.user.id %>", "<%= order_id %>");
break;
case "received":
dropin.setStatus('success', { message: 'Din bestillingen er mottatt! Vi venter på at transaksjonen skal fullføres.' });
break;
case "pending":
dropin.setStatus('success', { message: 'Din bestillingen er mottatt! Vi venter på at transaksjonen skal fullføres.' });
break;
case "cancelled":
send_event({
type: "order_" + result_code,
meta: {},
user_id: "<%= @context.user.id %>"
}, function() {});
show_error("Transaksjonen er kansellert!");
break;
case "refused":
send_event({
type: "order_" + result_code,
meta: {},
user_id: "<%= @context.user.id %>"
}, function() {});
show_error("Transaksjonen er avslått!");
break;
case "customernotfound":
show_error('Kombinasjon av adresse og fødselsnummer tilsvarer ikke offentlige poster. Sjekk detaljene dine.');
break;
case "billing_address_is_invalid":
show_error('Kombinasjon av adresse og fødselsnummer tilsvarer ikke offentlige poster. Sjekk detaljene dine.');
break;
case "customer_not_found_in_external_db":
show_error('Fødselsnummeret var feil.');
break;
case "negative_customer_score":
show_error('Vi kan dessverre ikke godkjenne betalingen din med AfterPay. Velg en annen betalingsmåte.');
break;
default:
send_event({
type: "order_" + result_code,
meta: {},
user_id: "<%= @context.user.id %>"
}, function() {});
send_error("ERROR: /flow/order/payment:onReady", result_code, "<%= @context.user.id %>", "<%= order_id %>");
show_error('Noe gikk galt.');
break;
}
<% else %>
var data = JSON.parse(getPaymentData());
data.details = <%= to_json(@context.params) %>;
var callback = function(httpRequest) {
if (httpRequest.readyState === 4) {
if (httpRequest.status >= 200 && httpRequest.status < 300) {
var response = JSON.parse(httpRequest.response);
handle_dropin_response(response, dropin);
} else if (httpRequest.status >= 400 && httpRequest.status < 500) {
var response = JSON.parse(httpRequest.response);
show_error(response.message);
} else {
show_error('Noe gikk galt.');
console.error(httpRequest.status, response);
}
}
};
post("/adyen/payment_details", {data: data}, callback);
<% end %>
<% end %>
}
})
.mount('#dropin');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment