Purpose:
The addTransaction function is used to create an invoice.
Return value:
Array - [invno, invoiceStatus]
The value of "invno" is the invoice number for the purchase.
The value of "invoiceStatus" shows if the invoice can be delivered immediately or requires manual approval.
1 = OK
2 = Pending
or
Throws an exception with error code and error message.
Code examples
Please note that you can find more code examples in our API-files which you will find under Download API in the left menu.
The code examples have been divided into several steps. Click on the step you would like to see the code example.
1. Initialize and setup the Klarna instance
$k = new Klarna();
$k->config(
123456, // Merchant ID
'sharedSecret', // Shared Secret
KlarnaCountry::SE, // Country
KlarnaLanguage::SV, // Language
KlarnaCurrency::SEK, // Currency
Klarna::BETA, // Server
'json', // PClass Storage
'/srv/pclasses.json', // PClass Storage URI path
true, // SSL
true // Remote logging of response times of xmlrpc calls
);
2. Add the article(s), shipping and/or handling fee
// Here we add a normal product to our goods list.
$k->addArticle(
4, // Quantity
"MG200MMS", // Article number
"Matrox G200 MMS", // Article name/title
299.99, // Price
25, // 25% VAT
0, // Discount
KlarnaFlags::INC_VAT // Price is including VAT.
);
// Next we might want to add a shipment fee for the product
$k->addArticle(
1,
"",
"Shipping fee",
14.5,
25,
0,
// Price is including VAT and is shipment fee
KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT
);
// Lastly, we want to use an invoice/handling fee as well
$k->addArticle(
1,
"",
"Handling fee",
11.5,
25,
0,
// Price is including VAT and is handling/invoice fee
KlarnaFlags::INC_VAT | KlarnaFlags::IS_HANDLING
);
3. Create and set the address(es)
// Create the address object and specify the values.
$addr = new KlarnaAddr(
'always_approved@klarna.com', // email
'', // Telno, only one phone number is needed.
'0762560000', // Cellno
'Testperson-se', // Firstname
'Approved', // Lastname
'', // No care of, C/O.
'Stårgatan 1', // Street
'12345', // Zip Code
'Ankeborg', // City
KlarnaCountry::SE, // Country
null, // HouseNo for German and Dutch customers.
null // House Extension. Dutch customers only.
);
// Next we tell the Klarna instance to use the address in the next order.
$k->setAddress(KlarnaFlags::IS_BILLING, $addr); // Billing / invoice address
$k->setAddress(KlarnaFlags::IS_SHIPPING, $addr); // Shipping / delivery address
4. Specify relevant information from your store (OPTIONAL)
// Set store specific information so you can e.g. search and associate invoices
// with order numbers.
$k->setEstoreInfo(
'175012', // Order ID 1
'1999110234', // Order ID 2
'' // Optional username, email or identifier
);
// If you don't have the order id available at this stage, you can later use the
// method updateOrderNo().
5. Set additional information (OPTIONAL)
/** Comment **/
$k->setComment('A text string stored in the invoice commentary area.');
/** Shipment type **/
// Normal shipment is defaulted, delays the start of invoice expiration/due-date.
$k->setShipmentInfo('delay_adjust', KlarnaFlags::EXPRESS_SHIPMENT);
6. Invoke addTransaction and transmit the data
try {
// Transmit all the specified data, from the steps above, to Klarna.
$result = $k->addTransaction(
'4103219202', // PNO (Date of birth for DE and NL).
null, // Gender.
KlarnaFlags::NO_FLAG, // Flags to affect behavior.
// -1, notes that this is an invoice purchase, for part payment purchase
// you will have a pclass object on which you use getId().
KlarnaPClass::INVOICE
);
// Check the order status
if ($result[1] == KlarnaFlags::PENDING) {
/* The order is under manual review and will be accepted or denied at a
later stage. Use cronjob with checkOrderStatus() or visit Klarna
Online to check to see if the status has changed. You should still
show it to the customer as it was accepted, to avoid further attempts
to fraud.
*/
}
// Here we get the invoice number
$invno = $result[0];
// Order is complete, store it in a database.
echo "Status: {$result[1]}\nInvno: {$result[0]}\n";
} catch(Exception $e) {
// The purchase was denied or something went wrong, print the message:
echo "{$e->getMessage()} (#{$e->getCode()})\n";
echo $e->getTraceAsString();
}
The code examples have been divided into several steps. Click on the step you would like to see the code example.
1. Initialize and setup the Klarna instance
API klarna = new API ();
/** Configure the Klarna object **/
klarna.Config (new KlarnaConfig () {
EID = 123456,
Secret = "sharedsecret",
Country = API.Country.Sweden,
Language = API.Language.Swedish,
Currency = API.Currency.SEK,
Encoding = API.Encoding.Swedish,
// API.KlarnaServer.Beta or API.KlarnaServer.Live, depending
// on which server your eid is associated with
Mode = API.KlarnaServer.Beta,
PCStorage = "xml",
PCURI = @"/tmp/pclasses.xml"
});
//It's important that we set the customers IP
klarna.ClientIP = "192.0.2.9";
// We are phasing out the previously used argument sessionId.
// You no longer need to implement the checkouthtml on your site
// but we still require a sessionId. In the future this argument
// will be completely removed but for now it needs to be set.
// To do this we will set it manually
int eid = 0; //Use the same estore id that was set up in the config
ThreatMetrix tm = new ThreatMetrix (eid);
SessionID sid = new SessionID ();
sid.DeviceID1 = tm.SessionID;
klarna.SessionID = sid;
2. Add the article(s), shipping and/or handling fee
//Here we add a normal product to our goods list
klarna.AddArticle (
4, //Quantity
"1234e", //Article number
"Matrox G200 MMS", //Article name/title
299.99, //Price
25, //VAT in %
0, //Discount in %
API.GoodsIs.IncVAT
);
//Here we add a shipment fee for the product
klarna.AddArticle (
1,
"",
"Shipment fee",
20.0,
25,
0,
API.GoodsIs.Shipping | API.GoodsIs.IncVAT
);
//Lastly, we want to use an invoice/handling fee as well
klarna.AddArticle (
1,
"",
"Handling fee",
10.0,
25,
0,
API.GoodsIs.Handling | API.GoodsIs.IncVAT
);
3. Create and set the address(es)
//Next we tell the Klarna instance to use the address in the next order.
//We start by specifying the shipping address:
ShippingAddress shippingAddress = new ShippingAddress (
"pending_approved@xxxxxx.xxx", //Email address
"", //Normal land line phone, we can skip this. Only one phone number needed
"0765260000", //Cellphone number
"Testperson-se", //First name
"Approved", //Last name
"", // C/O, Care of
"Stårgatan 1", //Street address. For DE and NL specify street number in houseNumber
"12345", //ZipCode
"Ankeborg", //City
API.Country.Sweden, //Country
"", //House number
"", //House exentions
"" //Company name
);
//And then the billing address:
BillingAddress billingAddress = new BillingAddress (
"pending_approved@xxxxxx.xxx", //Email address
"", //Normal land line phone, we can skip this. Only one phone number needed
"0765260000", //Cellphone number
"Testperson-se", //First name
"Approved", //Last name
"", // C/O, Care of
"Stårgatan 1", //Street address. For DE and NL specify street number in houseNumber
"12345", //ZipCode
"Ankeborg", //City
API.Country.Sweden, //Country
"", //House number
"", //House exentions
"" //Company name
);
//Set the addresses to our Klarna object
klarna.SetAddresses (shippingAddress, billingAddress);
4. Invoke AddTransaction and transmit the data
try {
string[] result = klarna.AddTransaction (
"410321-9202", // Personal Number. Use date of birth for DE / NL
null, //Gender
API.Flag.ReturnOCR,
// To combine two flags in one call use
// API.Flag.SensitiveOrder | API.Flag.ReturnOCR
(int)API.Flag.PclassInvoice, // -1 Notes that this is an invoice purchase, for part payment purchase you wil have a pclass object which you use pclass.PClassID from.
API.Encoding.Swedish //Encoding used
);
// Here we get the order status:
API.OrderStatus invoiceStatus = (API.OrderStatus)Convert.ToInt32 (result [2]);
// Check the order status
if (invoiceStatus == API.OrderStatus.Pending) {
/* The order is under manual review and will be accepted or
* denied at a later stage. Use cronjob with
* CheckOrderStatus() or visit Klarna Online to check to
* see if the status has changed. You should still show it
* to the customer as it was accepted, to avoid further
* attempts to fraud.
*/
Console.WriteLine ("Order is pending!");
}
// Here we get the invoice number:
string invoiceNumber = result [0];
// Here we get the OCR number
string ocrNumber = result [1];
// Order is complete, e.g. store it in a database.
Console.WriteLine ("invno: " + invoiceNumber);
Console.WriteLine ("ocr: " + ocrNumber);
} catch (Exception e) {
// Something went wrong print the error message:
Console.WriteLine ("Error : " + e.Message);
}
The code examples have been divided into several steps. Click on the step you would like to see the code example.
1. Initialize and setup the Klarna instance
Klarna k = new Klarna();
/*
* Configure the Klarna object using the config() method. (Alternative 1)
*/
/* KlarnaConfig conf = new KlarnaConfig();
// Define values:
conf.setEid(0); // Merchant ID or Estore ID, an Integer above 0.
conf.setSecret("sharedSecret"); // The shared secret which accompanied your eid.
conf.setCountry(KlarnaCountry.DE); // The country of your store.
conf.setLanguage(KlarnaLanguage.DE); // The language of your store.
conf.setCurrency(KlarnaCurrency.EUR); // The currency of your store.
conf.setMode(Klarna.BETA); // or Klarna.LIVE when you are ready to go live.
// Define pclass settings:
conf.setPcStorage("json"); // Storage module. Currently only json is supported.
conf.setPcURI("/srv/pclasses.json"); // Where the json file for the pclasses are stored.
// Should we use SSL?
conf.setSsl(false);
// Should we error report/status report to klarna.
conf.setCandice(true); // set to false if your server doesn't support UDP
// Do we want to see normal debug information?
conf.setDebug(null); // true to debug, null or false not to debug
// Set the config object.
k.config(conf);
*/
/*
* Configure the Klarna object using the config() method (Alternative 2)
*/
/*
* k.config(0, // e-store ID
* "sharedSecret", // shared secret
* KlarnaCountry.DE, // Country constant
* KlarnaLanguage.DE, // Language constant
* KlarnaCurrency.EUR, // Currency constant
* Klarna.BETA, // Mode, BETA or LIVE
* "json", // Storage module
* "/srv/pclasses.json", // Storage location
* true, // SSL
* true // Candice
* );
*
* k.debug = false;
*/
/*
* Configure the Klarna object using the config() method (Alternative 3)
*/
k.config(KlarnaConfig.fromJson("/srv/klarna.json"));
/* the file would contain the following data to set the same information as above alternatives:
* {
* "eid":0,
* "secret":"sharedSecret",
** "country":"DE",
** "language":"DE",
* "currency":"EUR",
* "mode":1,
* "ssl":false,
* "candice":true,
* "pcStorage":"json",
* "pcURI":"/srv/pclasses.json"
* }
*
*/
2. Add the article(s), shipping and/or handling fee
// Here we add a normal product to our goods list.
k.addArticle(4, // Quantity
"MG200MMS", // Article number
"Matrox G200 MMS", // Article name/title
299.99, // Price
19d, // 19% VAT. a double
0d, // Discount, a double
KlarnaFlags.Goods.INC_VAT.intVal()); // Price is including VAT
//Next we might want to add a shipment fee for the product
int shipFlag = KlarnaFlags.Goods.INC_VAT.intVal() + KlarnaFlags.Goods.IS_SHIPMENT.intVal(); // Some flags can be added together.
k.addArticle(1,
"",
"Shipping fee",
4.5,
19d,
0d,
shipFlag); // Price is including VAT and is shipment fee
k.addArticle(1,
"",
"Handling fee",
1.5,
19d,
0d, // Flags can be added together in the method call aswell.
KlarnaFlags.Goods.INC_VAT.intVal() + KlarnaFlags.Goods.IS_HANDLING.intVal()); // Price is including VAT and is handling/invoice fee
3. Create and set the address(es)
//Create the address object and specify the values.
KlarnaAddr addr = new KlarnaAddr(
"test@example.com", // Email address
"", // We skip the normal land line phone. only one is needed.
"01522113356", // Mobile number
"Testperson-de", // First (given) name
"Approved", // Last (family) name
"", // no care of ( c/o )
"Hellersbergstrasse", // for DE and NL specify street number in houseNo
"41460", // Zip code
"Neuss", // City
KlarnaCountry.DE, // KlarnaCountry constant
"14",
null);
//There are also set/get methods to do the same thing, like:
addr.setEmail("test@example.com");
// Next we tell the klarna instance to use the address in the next order.
k.setAddress(KlarnaFlags.Address.IS_BILLING, addr); // Billing / invoice address
k.setAddress(KlarnaFlags.Address.IS_SHIPPING, addr); // Shipping / delivery address
4. Specify relevant information from your store (OPTIONAL)
k.setEstoreInfo(
"987654", // Maybe the estores order number/id
"1234567890", // Could be an order number from another system?
"" // Username, email or identifier for the user?
);
// another option is to omit the last field entirely.
//If you don't have the order id available at this stage, you can later use the method updateOrderNo().
5. Set additional information (OPTIONAL)
// A comment maybe?
k.setComment("A text string stored in the invoice commentary area.");
// Session IDs?
/* We are phasing out the previously used argument session_id.
you no longer need to implement the checkouthtml on your site but we still require a session_id.
In the future this argument will be completely removed but for now it needs to be set. */
k.setSessionID("dev_id_1", "2425967623052370772757633156976982469681");
// Shipment type?
k.setShipmentInfo("delay_adjust", KlarnaFlags.Shipment.EXPRESS_SHIPMENT);
/* If a company is shopping, reference has to be set. */
if (addr.isCompany()) {
k.setReference("Reference Code");
}
6. Invoke addTransaction and transmit the data
try {
k.setClientIP(request.getRemoteAddr());
String[] result = k.addTransaction(
"07071960", // Date of Birth for DE
KlarnaFlags.Gender.MALE, // Customer is male
KlarnaFlags.NO_FLAG, // No specific behaviour like RETURN_OCR or TEST_MODE
KlarnaPClass.INVOICE);
//Check the order status
KlarnaFlags.OrderStatus status = KlarnaFlags.OrderStatus.get(Integer.parseInt(result[1])); // An example of how you could do it.
if (status == KlarnaFlags.OrderStatus.PENDING) {
out.println(status.getText()); // Outputs "PENDING".
/* The order is under manual review and will be accepted or denied at a later stage.
Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed.
You should still show it to the customer as it was accepted, to avoid further attempts to fraud. */
}
//Here we get the invoice number
String invNo = result[0];
//Order is complete, store it in a database.
} catch (Exception ex) {
//The purchase was denied or something went wrong, print the message:
out.println(ex.getMessage());
}
The code examples have been divided into several steps. Click on the step you would like to see the code example.
1. Initialize and setup the Klarna instance
<%
Option Explicit
%>
<%
' Grab the API object
' -Merchant ID or Estore ID, an integer above 0.
' -The shared secret which accompanied your eid.
' -Country, language and currency.
Dim kAPI
Set kAPI = GetKlarna(0, "sharedsecret", "SE", "SV", "SEK")
' Do we want to see normal debug information?
kAPI.DebugInformation = True
' Set the address and port to Klarna server.
' Use LIVE or BETA depending on which server your eid is associated with.
kAPI.SetPort(HTTPS_PORT) ' or HTTP_PORT
kAPI.SetHost(BETA_HOST) ' or LIVE_HOST
' Where the XML for the PClasses are stored, e.g. "pclasses.xml"
kAPI.SetPClassesStorageUri(Server.MapPath("pclasses.xml"))
%>
2. Add the article(s), shipping and/or handling fee
<%
' Here we add a normal product to our goods list.
' -Quantity
' -Article number
' -Article name/title
' -Price
' -VAT, 25% VAT
' -Discount
' -Flags, price including VAT
Call kAPI.AddArticle(4, "MG200MMS", "Matrox G200 MMS", 299.99, 25, 0, INC_VAT)
' Next we might want to add a shipment fee for the product
Call kAPI.AddArticle(1, "", "Shipping fee", 40, 25, 0, INC_VAT + IS_SHIPMENT)
' Lastly, we want to use an invoice/handling fee as well
Call kAPI.AddArticle(1, "", "Handling fee", 10, 25, 0, INC_VAT + IS_HANDLING)
%>
3. Create and set the address(es)
<%
' Create the address object.
Dim address
Set address = new KlarnaAddr
' Specify the customers details.
address.setEmail("always_accepted@klarna.se")
address.setTelno("") ' We skip the normal land line phone, only one is needed.
address.setCellno("0765260000")
address.setFirstName("Testperson-se")
address.setLastName("Approved")
address.setCompanyName("") ' No company name
address.setCareof("") ' No care of, C/O
address.setStreet("Stårgatan 1") ' For DE and NL specify street number with setHouseNumber.
address.setHouseNumber("") ' Only required for DE / NL
address.setHouseExt("") ' Only required for NL.
address.setZipCode("12345")
address.setCity("Ankeborg")
address.setCountry(COUNTRY_SE)
' Next we tell the Klarna instance to use the address in the next order.
Call kAPI.SetAddress(IS_BILLING, address) ' Billing / invoice address
Call kAPI.SetAddress(IS_SHIPPING, address) ' Shipping / delivery address
%>
4. Specify relevant information from your store (OPTIONAL)
<%
' Set store specific information so you can e.g. search and associate invoices with order numbers.
' -Order id 1, maybe the estore's order number/id?
' -Order id 2, could be an order number from another system?
' -User, Username, email or identifier for the user?
Call kAPI.SetEstoreInfo("175012", "1999110234", "")
' If you don't have the order id available at this stage, you can later use the method updateOrderNo().
%>
5. Set additional information
<%
' Comment? (OPTIONAL)
kAPI.SetComment("A text string stored in the invoice commentary area.")
' Shipment type?
' Normal shipment is defaulted, delays the start of invoice expiration/due-date.
Call kAPI.SetShipmentInfo("delay_adjust", EXPRESS_SHIPMENT)
%>
6. Invoke addTransaction and transmit the data
<%
On Error Resume Next
' Transmit all the specified data, from the steps above, to Klarna.
' -pno, Date of birth for DE.
' -gender, The customer is a male.
' -flags, No specific behaviour like RETURN_OCR or TEST_MODE.
' -pclass, -1, notes that this is an invoice purchase, for part payment purchase you will have a pclass object on which you use getId().
' -encoding, null to automatically use it for DE.
Dim result
result = kAPI.AddTransaction("410321-9202", null, NO_FLAG, PCLASS_INVOICE, null, true)
If Err.number = 0 Then
' Success
'Check the order status
If result(1) = PENDING Then
' The order is under manual review and will be accepted or denied at a later stage.
' Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed.
' You should still show it to the customer as it was accepted, to avoid further attempts to fraud.
End If
' Here we get the invoice number
Dim invoiceNumber
invoiceNumber = result(0)
' Order is complete, store it in a database.
Response.Write("Invoice #" & invoiceNumber)
Else
' Something went wrong
Response.Write("Error occured: " & Err.number & " - " & Err.Description & "" & Err.Source & "")
End If
%>
