@mia-burton/klarna-node
Version:
A Node.js module for Klarna
164 lines (163 loc) • 7.02 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
const axios_1 = require("axios");
const types_1 = require("./types");
const errors_1 = require("./errors");
const builders_1 = require("./builders");
const mappers_1 = require("./mappers");
const builders_2 = require("./builders");
const order_mapper_1 = require("./mappers/order.mapper");
const utils_1 = require("./utils");
class Client {
/**
* Create a Klarna client
* @param uid string - Api key given from Klarna
* @param password string - Password given from Klarna
* @param live boolean - Switch live sandbox env
*/
constructor(uid, password, location, live = true) {
this.uid = uid;
this.password = password;
this.live = live;
this.setLocation(location);
this.restClient = this.initAxios();
}
setLocation(location) {
switch (location) {
case types_1.Location.America:
this.baseUrl = this.live ? 'https://api-na.klarna.com/' : 'https://api-na.playground.klarna.com/';
break;
case types_1.Location.Europe:
this.baseUrl = this.live ? 'https://api.klarna.com/' : 'https://api.playground.klarna.com/';
break;
case types_1.Location.Oceania:
this.baseUrl = this.live ? 'https://api-oc.klarna.com/' : 'https://api-oc.playground.klarna.com/';
break;
default:
throw new Error('Invalid location');
}
this.restClient = this.initAxios();
}
/**
* @param theOrder
* @param urls Insert {session.id} and/or {order.id} as placeholder
* @return Promise<SessionResponse>
* @throws CreateSessionError
*/
createPaymentSession(theOrder, urls) {
return __awaiter(this, void 0, void 0, function* () {
try {
const bodyBuilder = new builders_1.SessionBodyBuilder();
const body = bodyBuilder.build(theOrder, urls);
const res = yield this.restClient.post('payments/v1/sessions', body);
const session = new types_1.SessionResponse(res.data.session_id, res.data.client_token);
return session;
}
catch (err) {
if (axios_1.default.isAxiosError(err)) {
throw new errors_1.CreateSessionError(err.message, err.response ? err.response.data : {});
}
throw new errors_1.CreateSessionError(err.message, err);
}
});
}
getPaymentSession(theId) {
return __awaiter(this, void 0, void 0, function* () {
try {
const res = yield this.restClient.get(`payments/v1/sessions/${theId}`);
return new mappers_1.PaymentSessionMapper().map(res.data);
}
catch (err) {
if (axios_1.default.isAxiosError(err)) {
throw new errors_1.ReadSessionError(err.message, err.response ? err.response.data : {});
}
throw new errors_1.ReadSessionError(err.message, err);
}
});
}
/**
* @param theOrder
* @returns Promise<OrderResponse>
* @throws CreateOrderError
*/
createOrder(theSessionId) {
return __awaiter(this, void 0, void 0, function* () {
try {
const paymentSesison = yield this.getPaymentSession(theSessionId);
if (paymentSesison.status === 'incomplete' && paymentSesison.clientToken && paymentSesison.authorizationToken) {
const bodyBuilder = new builders_2.OrderBodyBuilder();
const body = bodyBuilder.build(paymentSesison);
const res = yield this.restClient.post(`payments/v1/authorizations/${paymentSesison.authorizationToken}/order`, body);
const order = new types_1.OrderResponse(res.data.order_id, res.data.fraud_status);
return order;
}
throw new errors_1.CreateOrderError('Session not valid', {});
}
catch (err) {
if (axios_1.default.isAxiosError(err)) {
throw new errors_1.CreateOrderError(err.message, err.response ? err.response.data : {});
}
throw new errors_1.CreateOrderError(err.message, err);
}
});
}
/**
* @param theId
* @returns {Promise<Order>}
*/
getOrder(theId) {
return __awaiter(this, void 0, void 0, function* () {
try {
const res = yield this.restClient.get(`ordermanagement/v1/orders/${theId}`);
return new order_mapper_1.OrderMapper().map(res.data);
}
catch (err) {
if (axios_1.default.isAxiosError(err)) {
throw new errors_1.ReadOrderError(err.message, err.response ? err.response.data : {});
}
throw new errors_1.ReadOrderError(err.message, err);
}
});
}
/**
* Create a capture for the givend order of the given amount
* @param theOrderId
* @param theAmount
* @returns {Promise<string>}
*/
captureOrder(theOrderId, theAmount) {
return __awaiter(this, void 0, void 0, function* () {
try {
const res = yield this.restClient.post(`ordermanagement/v1/orders/${theOrderId}/captures`, { captured_amount: utils_1.Utils.formatPrice(theAmount) });
return res.headers['capture-id'];
}
catch (err) {
if (axios_1.default.isAxiosError(err)) {
throw new errors_1.ReadOrderError(err.message, err.response ? err.response.data : {});
}
throw new errors_1.ReadOrderError(err.message, err);
}
});
}
initAxios() {
return axios_1.default.create({
baseURL: this.baseUrl,
headers: {
Authorization: `Basic ${Buffer.from(`${this.uid}:${this.password}`).toString('base64')}`,
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
}
}
exports.Client = Client;