This guide walks through building an automated evidence pipeline for Klarna disputes. The pipeline receives a dispute webhook, pulls order and carrier data, assembles evidence to Klarna's Proof of Delivery (POD) expectations, validates it, and submits it through the Klarna dispute API before the deadline. It covers the two reasons that generate most delivery-related losses: item not received (INR) and Significant Deviation (item materially different from what was ordered).
It's written for e-commerce engineers and the risk or operations leads who own dispute outcomes. Expect moderate to high difficulty. A single-carrier MVP is realistic in one to two weeks of engineering time. Production hardening (multi-carrier adapters, monitoring, fallbacks) typically adds several more weeks. Both figures are planning estimates and depend on how clean your OMS data is.
What you need before you start
Read access to order, line item, and fulfillment data in your OMS or storefront platform.
API access to your carriers or fulfillment provider, including tracking events and delivery proof artifacts.
Klarna dispute API credentials and a public HTTPS endpoint for dispute webhooks.
A job queue (SQS, RabbitMQ, BullMQ, or similar) and a relational store with unique constraints.
Node.js 20+ if you want to run the snippets as written. The logic ports directly to Python.
A note on the code: Klarna's Payment Dispute API reference defines the authoritative endpoints, webhook events, and field names. It covers dispute details, accepting a loss, attachment upload and download, representment responses, and appeals. The payloads below are mock structures that match the evidence schema in this guide. Verify every path, header, and field against the current Klarna reference before production use.
Define success before you write code
Treat the pipeline as done when it meets four conditions:
Every dispute is mapped to the right internal type (INR or Significant Deviation) with an audit trail.
Evidence contains the fields Klarna expects for that reason, and POD eligibility checks pass before anything is submitted.
Submission happens before an internal submit-by time that sits ahead of Klarna's deadline.
Failures retry automatically, and anything that can't be resolved reaches a human with enough context to act.
Step 1: Lay out the architecture
Keep the system as five small components with clear boundaries:
A webhook intake service that verifies, stores, and enqueues. It does no other work.
An evidence worker that runs the job lifecycle.
Provider adapters: one for your OMS, one per carrier. Each returns data in your internal schema, never the raw vendor shape.
A data store holding events, jobs, evidence packages, and validation reports.
A Klarna disputes API client that owns auth, retries, and attachment upload.
The integration touchpoints, in order of execution:
Dispute webhook arrives on a state change.
Worker fetches the dispute details from Klarna to get the reason, state, and deadline.
Worker fetches order and line items from the OMS.
Worker fetches tracking and POD from the carrier.
Worker assembles, validates, and submits evidence.
Later webhooks (representment, outcome) update the case state.
Use the Klarna dispute ID as the primary key for everything. Duplicate and out-of-order webhooks are normal, and a unique key on dispute ID plus event ID makes them harmless.
Step 2: Classify the dispute and route evidence logic
Normalize Klarna's reason values into your own enum on the first fetch. Don't let Klarna's strings leak into downstream code, because reason names and sub-reasons change between API versions.
Internal type
Evidence required
Validation gate
Output
INR
Tracking ID, carrier, delivery timestamp, full recipient name, shipping address, POD artifact
POD eligibility (identity, address match, artifact type, signature above threshold)
POD evidence package + attachments
SIGNIFICANT_DEVIATION
Product description snapshot at purchase, SKU/variant, fulfilled item record, customer communications, return/refund records
The UNKNOWN row matters. Any reason code your mapper doesn't recognize should route to a human, never to a default evidence type. Submitting delivery proof against a product-quality claim wastes your one response window.
Log the raw Klarna reason, the mapped type, and the mapper version on every case. When routing is wrong, that record is how you find out why.
Step 3: Build the evidence schema
Define one schema your pipeline produces regardless of carrier or dispute type. Adapters write into it, validators read from it, and the Klarna client serializes from it.
{"evidence_version":3,"dispute_id":"dsp_mock_8841","dispute_type":"INR","order":{"order_id":"SO-10492","placed_at":"2026-09-14T09:12:44Z","total":{"amount":912.40,"currency":"EUR"},"line_items":[{"sku":"CHAIR-OAK-02","name":"Oak chair","qty":2}]},"recipient":{"full_name":"Anna de Vries","address":{"line1":"Keizersgracht 123","line2":"2","postal_code":"1015 CJ","city":"Amsterdam","country":"NL"}},"shipment":{"carrier":"mock-carrier","tracking_id":"MC123456789NL","delivered_at":"2026-09-17T13:41:09Z","status":"DELIVERED"},"pod":{"artifact_type":"SIGNATURE","signer_name":"A. de Vries","artifact_url":"https://carrier.example/pod/MC123456789NL.pdf","geo":{"lat":52.3731,"lng":4.8922,"accuracy_m":12},"address_match":{"score":0.97,"method":"normalized_fuzzy"}},"validation":{"passed":true,"rules":[]}}
{"evidence_version":3,"dispute_id":"dsp_mock_8841","dispute_type":"INR","order":{"order_id":"SO-10492","placed_at":"2026-09-14T09:12:44Z","total":{"amount":912.40,"currency":"EUR"},"line_items":[{"sku":"CHAIR-OAK-02","name":"Oak chair","qty":2}]},"recipient":{"full_name":"Anna de Vries","address":{"line1":"Keizersgracht 123","line2":"2","postal_code":"1015 CJ","city":"Amsterdam","country":"NL"}},"shipment":{"carrier":"mock-carrier","tracking_id":"MC123456789NL","delivered_at":"2026-09-17T13:41:09Z","status":"DELIVERED"},"pod":{"artifact_type":"SIGNATURE","signer_name":"A. de Vries","artifact_url":"https://carrier.example/pod/MC123456789NL.pdf","geo":{"lat":52.3731,"lng":4.8922,"accuracy_m":12},"address_match":{"score":0.97,"method":"normalized_fuzzy"}},"validation":{"passed":true,"rules":[]}}
{"evidence_version":3,"dispute_id":"dsp_mock_8841","dispute_type":"INR","order":{"order_id":"SO-10492","placed_at":"2026-09-14T09:12:44Z","total":{"amount":912.40,"currency":"EUR"},"line_items":[{"sku":"CHAIR-OAK-02","name":"Oak chair","qty":2}]},"recipient":{"full_name":"Anna de Vries","address":{"line1":"Keizersgracht 123","line2":"2","postal_code":"1015 CJ","city":"Amsterdam","country":"NL"}},"shipment":{"carrier":"mock-carrier","tracking_id":"MC123456789NL","delivered_at":"2026-09-17T13:41:09Z","status":"DELIVERED"},"pod":{"artifact_type":"SIGNATURE","signer_name":"A. de Vries","artifact_url":"https://carrier.example/pod/MC123456789NL.pdf","geo":{"lat":52.3731,"lng":4.8922,"accuracy_m":12},"address_match":{"score":0.97,"method":"normalized_fuzzy"}},"validation":{"passed":true,"rules":[]}}
For INR, the minimum viable POD set matches what Guzco builds to Klarna's POD spec: tracking ID, full recipient name, a shipping address match, and a signature for orders above 750 USD (or equivalent). Klarna's Merchant Protection Program (July 2026) lists signature, OTP, or authorized QR as accepted proof types above that value and keeps proof for 180 days after activation. Make artifact_type an enum that includes all three.
For Significant Deviation, store immutable snapshots at order time: product title, description, variant attributes, and images as they appeared when the customer paid. Reconstructing the listing after a dispute opens is unreliable. Add fulfilled-item records (pick/pack SKU scans if you have them) and any customer messages about the item.
One distinction drives the whole design: a tracking update that says "delivered" is not eligible POD. Eligibility means the identity, address, and artifact requirements are all satisfied. Treat that as a hard gate in Step 7.
Step 4: Implement webhook intake
The intake service does four things: verify the signature, persist the raw payload, enqueue a job, and return 200. Anything slower risks webhook retries and duplicate deliveries.
importexpressfrom"express";importcryptofrom"node:crypto";import{db,queue}from"./infra.js";constapp = express();functionverify(rawBody,signature){// Mock HMAC scheme. Use the verification method defined for your Klarna webhook setup.constexpected = crypto
.createHmac("sha256",process.env.KLARNA_WEBHOOK_SECRET)
.update(rawBody)
.digest("hex");returnsignature && crypto.timingSafeEqual(Buffer.from(expected),Buffer.from(signature));}app.post("/webhooks/klarna-disputes",express.raw({type:"application/json"}),async(req,res)=>{if(!verify(req.body,req.get("x-signature")))returnres.sendStatus(401);constevent = JSON.parse(req.body.toString());constinserted = awaitdb.query(`INSERT INTO dispute_events (event_id, dispute_id, payload)
VALUES ($1, $2, $3) ON CONFLICT (event_id) DO NOTHING RETURNING event_id`,[event.event_id,event.dispute_id,event]);if(inserted.rowCount === 1){awaitqueue.add("evidence-build",{disputeId:event.dispute_id,eventId:event.event_id});}res.sendStatus(200);});
importexpressfrom"express";importcryptofrom"node:crypto";import{db,queue}from"./infra.js";constapp = express();functionverify(rawBody,signature){// Mock HMAC scheme. Use the verification method defined for your Klarna webhook setup.constexpected = crypto
.createHmac("sha256",process.env.KLARNA_WEBHOOK_SECRET)
.update(rawBody)
.digest("hex");returnsignature && crypto.timingSafeEqual(Buffer.from(expected),Buffer.from(signature));}app.post("/webhooks/klarna-disputes",express.raw({type:"application/json"}),async(req,res)=>{if(!verify(req.body,req.get("x-signature")))returnres.sendStatus(401);constevent = JSON.parse(req.body.toString());constinserted = awaitdb.query(`INSERT INTO dispute_events (event_id, dispute_id, payload)
VALUES ($1, $2, $3) ON CONFLICT (event_id) DO NOTHING RETURNING event_id`,[event.event_id,event.dispute_id,event]);if(inserted.rowCount === 1){awaitqueue.add("evidence-build",{disputeId:event.dispute_id,eventId:event.event_id});}res.sendStatus(200);});
importexpressfrom"express";importcryptofrom"node:crypto";import{db,queue}from"./infra.js";constapp = express();functionverify(rawBody,signature){// Mock HMAC scheme. Use the verification method defined for your Klarna webhook setup.constexpected = crypto
.createHmac("sha256",process.env.KLARNA_WEBHOOK_SECRET)
.update(rawBody)
.digest("hex");returnsignature && crypto.timingSafeEqual(Buffer.from(expected),Buffer.from(signature));}app.post("/webhooks/klarna-disputes",express.raw({type:"application/json"}),async(req,res)=>{if(!verify(req.body,req.get("x-signature")))returnres.sendStatus(401);constevent = JSON.parse(req.body.toString());constinserted = awaitdb.query(`INSERT INTO dispute_events (event_id, dispute_id, payload)
VALUES ($1, $2, $3) ON CONFLICT (event_id) DO NOTHING RETURNING event_id`,[event.event_id,event.dispute_id,event]);if(inserted.rowCount === 1){awaitqueue.add("evidence-build",{disputeId:event.dispute_id,eventId:event.event_id});}res.sendStatus(200);});
Return 200 for duplicates as well. A non-2xx on a replay only generates more replays.
The worker then moves each case through a fixed lifecycle: RECEIVED → DATA_FETCH → EVIDENCE_ASSEMBLY → VALIDATION → SUBMIT → CONFIRM (or RETRY). Persist the state after each transition, along with these checkpoint fields: dispute ID, Klarna deadline, internal submit-by time, evidence_version, adapter versions, and submission response IDs. When a case fails at 2 a.m., these fields tell you which stage and which adapter to look at.
Checkpoint: replay the same webhook twice with curl. You should see two rows' worth of intake attempts, one stored event, and one queued job.
Step 5: Pull tracking and POD from the carrier
Wrap each carrier in an adapter with a single method that returns the shipment and pod sections of the schema. Never pass vendor JSON beyond the adapter.
Two details save time later. First, flag errors as retryable or not at the adapter boundary, so the worker's retry policy stays generic. Second, download the POD artifact and store your own copy. Carrier-hosted links expire, and you need the file on hand at submit time and for any representment.
Step 6: Normalize and match addresses
Address mismatch is the most common reason a delivered parcel fails validation. The OMS says Keizersgracht 123, 2, and the carrier recorded KEIZERSGRACHT 123-2. Both are correct, and a naive string comparison rejects them.
Normalize both sides identically before comparing:
Uppercase, trim, collapse whitespace, and strip diacritics (NFD then remove combining marks).
Standardize the country to ISO 3166-1 alpha-2.
Format the postal code per country (remove spaces and hyphens, then reapply the national pattern).
Expand or contract street suffixes consistently (str. and straat, ave and avenue).
Split unit or suite numbers from the house number into their own field.
Use a strict gate on country and postal code, and a fuzzy threshold only on the street and unit tokens. A threshold around 0.85 is a reasonable starting point. Tune it against labeled historical cases, and don't raise it blindly, because a mismatch that's really a formatting difference is exactly what you want to pass.
Watch for three traps. Unit omissions: the carrier drops line2 for apartment buildings, so fall back to street plus postal plus signer name. PO boxes and pickup points: a parcel delivered to a locker won't match the home address by design, so handle it as its own delivery method and don't force an address comparison. Transposed fields: some checkouts put the house number in line2, so test your OMS mapping with real orders.
Step 7: Validate POD eligibility before you submit
Run a rule engine over the assembled package and write the result to a validation report. Rules should be small, named, and independent.
exportfunctionvalidatePod(pkg,thresholdUsd = 750){constfailures = [];const{shipment,pod,recipient,order} = pkg;if(!shipment.tracking_id)failures.push("MISSING_TRACKING_ID");if(shipment.status !== "DELIVERED" || !shipment.delivered_at)failures.push("NOT_DELIVERED");if(!recipient.full_name?.trim().includes(" "))failures.push("RECIPIENT_NOT_FULL_NAME");if(!pod || pod.artifact_type === "NONE")failures.push("NO_POD_ARTIFACT");if(pod?.address_match?.score < 0.85)failures.push("ADDRESS_MISMATCH");constusd = toUsd(order.total);// use your own FX sourceif(usd > thresholdUsd && !["SIGNATURE","OTP","AUTHORIZED_QR"].includes(pod?.artifact_type)){failures.push("HIGH_VALUE_REQUIRES_STRONG_PROOF");}return{passed:failures.length === 0,rules:failures,checked_at:newDate().toISOString()};}
exportfunctionvalidatePod(pkg,thresholdUsd = 750){constfailures = [];const{shipment,pod,recipient,order} = pkg;if(!shipment.tracking_id)failures.push("MISSING_TRACKING_ID");if(shipment.status !== "DELIVERED" || !shipment.delivered_at)failures.push("NOT_DELIVERED");if(!recipient.full_name?.trim().includes(" "))failures.push("RECIPIENT_NOT_FULL_NAME");if(!pod || pod.artifact_type === "NONE")failures.push("NO_POD_ARTIFACT");if(pod?.address_match?.score < 0.85)failures.push("ADDRESS_MISMATCH");constusd = toUsd(order.total);// use your own FX sourceif(usd > thresholdUsd && !["SIGNATURE","OTP","AUTHORIZED_QR"].includes(pod?.artifact_type)){failures.push("HIGH_VALUE_REQUIRES_STRONG_PROOF");}return{passed:failures.length === 0,rules:failures,checked_at:newDate().toISOString()};}
exportfunctionvalidatePod(pkg,thresholdUsd = 750){constfailures = [];const{shipment,pod,recipient,order} = pkg;if(!shipment.tracking_id)failures.push("MISSING_TRACKING_ID");if(shipment.status !== "DELIVERED" || !shipment.delivered_at)failures.push("NOT_DELIVERED");if(!recipient.full_name?.trim().includes(" "))failures.push("RECIPIENT_NOT_FULL_NAME");if(!pod || pod.artifact_type === "NONE")failures.push("NO_POD_ARTIFACT");if(pod?.address_match?.score < 0.85)failures.push("ADDRESS_MISMATCH");constusd = toUsd(order.total);// use your own FX sourceif(usd > thresholdUsd && !["SIGNATURE","OTP","AUTHORIZED_QR"].includes(pod?.artifact_type)){failures.push("HIGH_VALUE_REQUIRES_STRONG_PROOF");}return{passed:failures.length === 0,rules:failures,checked_at:newDate().toISOString()};}
Store the report next to the package, even on success. It's your audit record and the first thing a dispute specialist reads when a case is lost. The 750 USD figure follows Guzco's Klarna POD specification and the Merchant Protection Program wording. Make it configurable and re-check it against Klarna's current terms, since thresholds are policy and can change.
A failed gate doesn't mean the case is lost. It means the worker re-fetches tracking on a schedule (POD artifacts often land hours after the "delivered" scan) and only escalates to manual review when the submit-by time approaches.
Checkpoint: run the validator against three fixtures: a delivered signed parcel, a delivered parcel with no artifact, and a high-value order with a plain "left at door" scan. Expected results: pass, NO_POD_ARTIFACT, and HIGH_VALUE_REQUIRES_STRONG_PROOF (the second fixture also fails on the high-value rule if it exceeds the threshold).
Step 8: Submit with a deadline buffer
Never schedule submission against Klarna's deadline directly. Compute an internal submit-by time and treat it as the real deadline.
Always read the deadline from the dispute payload. The Stripe dispute documentation in Guzco's knowledge base describes Klarna-related timing such as a 180-calendar-day filing limit and escalation after 21 calendar days if unresolved. Use those numbers to size your buffer and your retry schedule, not as hardcoded cutoffs. Guzco's Klarna solution works the same way: deadlines are monitored in real time, and its page shows an example case filed 11 hours before the deadline.
Submission then follows this sequence:
exportasyncfunctionsubmitEvidence(pkg,files){constdispute = awaitklarna.get(`/disputes/${pkg.dispute_id}`);// mock pathif(!["EVIDENCE_REQUESTED","REPRESENTMENT_REQUESTED"].includes(dispute.state)){return{skipped:true,reason:`state=${dispute.state}`};}for(constfoffiles){awaitklarna.upload(`/disputes/${pkg.dispute_id}/attachments`,{filename:f.name,// e.g. SO-10492_pod_signature.pdfcontentType:f.mime,// application/pdf, image/jpegbody:f.buffer,});}constres = awaitklarna.post(`/disputes/${pkg.dispute_id}/response`,{reason:pkg.dispute_type,summary:buildSummary(pkg),evidence:pkg,// mock: serialize per Klarna's documented fields});return{response_id:res.id,accepted:res.status === "ACCEPTED"};}
exportasyncfunctionsubmitEvidence(pkg,files){constdispute = awaitklarna.get(`/disputes/${pkg.dispute_id}`);// mock pathif(!["EVIDENCE_REQUESTED","REPRESENTMENT_REQUESTED"].includes(dispute.state)){return{skipped:true,reason:`state=${dispute.state}`};}for(constfoffiles){awaitklarna.upload(`/disputes/${pkg.dispute_id}/attachments`,{filename:f.name,// e.g. SO-10492_pod_signature.pdfcontentType:f.mime,// application/pdf, image/jpegbody:f.buffer,});}constres = awaitklarna.post(`/disputes/${pkg.dispute_id}/response`,{reason:pkg.dispute_type,summary:buildSummary(pkg),evidence:pkg,// mock: serialize per Klarna's documented fields});return{response_id:res.id,accepted:res.status === "ACCEPTED"};}
exportasyncfunctionsubmitEvidence(pkg,files){constdispute = awaitklarna.get(`/disputes/${pkg.dispute_id}`);// mock pathif(!["EVIDENCE_REQUESTED","REPRESENTMENT_REQUESTED"].includes(dispute.state)){return{skipped:true,reason:`state=${dispute.state}`};}for(constfoffiles){awaitklarna.upload(`/disputes/${pkg.dispute_id}/attachments`,{filename:f.name,// e.g. SO-10492_pod_signature.pdfcontentType:f.mime,// application/pdf, image/jpegbody:f.buffer,});}constres = awaitklarna.post(`/disputes/${pkg.dispute_id}/response`,{reason:pkg.dispute_type,summary:buildSummary(pkg),evidence:pkg,// mock: serialize per Klarna's documented fields});return{response_id:res.id,accepted:res.status === "ACCEPTED"};}
Retry by failure type:
Carrier timeout or 5xx: exponential backoff with jitter, capped, until submit-by minus one hour.
Validation failure: retry only after a scheduled tracking re-fetch, since repeating the same data produces the same failure.
Klarna 429 or 5xx: backoff and retry, reusing an idempotency key derived from dispute ID and evidence_version.
Klarna 4xx (bad state, bad attachment): don't retry blindly. Re-read the dispute state and route to review.
Finish each submission with a confirmation checklist: Klarna returned an accepted response, attachments are listed against the dispute, the response ID is stored, and the case state is CONFIRM.
Step 9: Test and monitor before you trust it
For testing, build fixtures for both dispute types, plus the awkward cases: delivered with no POD, partial tracking, address with unit omitted, locker delivery, and duplicate webhooks arriving out of order. Unit-test the normalizer and every validation rule in isolation. Replace carrier calls with recorded responses so tests don't depend on a live API.
In production, track these metrics:
Webhook intake failures and replay counts.
Evidence-build latency, p50 and p95, per carrier.
Adapter error rate per carrier.
Validation failure rate by rule name.
Submission success rate and time-to-submit relative to the Klarna deadline.
Alert on a case within a few hours of submit-by that hasn't passed validation, a validation rule failing repeatedly across cases (usually an adapter regression), and event sequences that shouldn't happen, such as an outcome webhook before any submission.
Write short playbooks for the three situations that always occur: no POD, where the worker keeps re-fetching and escalates at a set time; partial tracking, where you contact the carrier for a POD copy; and address mismatch, where a specialist reviews both address records and decides whether to submit with an explanation. Deciding when to contest at all is a separate judgment, covered in this merchant dispute playbook.
POD exists in the carrier portal but your package says NO_POD_ARTIFACT. The adapter is reading the delivery event before the artifact is attached. Add scheduled re-fetches (for example at 1, 4, and 12 hours) and confirm your mapArtifact handles every proof type the carrier returns.
Address score is low on a correct delivery. Print the normalized forms side by side. The cause is almost always a field mapping problem (house number in line2) or a suffix you haven't standardized.
Evidence arrives for the wrong reason. Check the stored raw reason and mapper version. Unknown reasons should land in UNKNOWN. If they're defaulting to INR, fix the mapper's fallback.
Klarna rejects an attachment. Check the file name, MIME type, and size against the current API reference. Use deterministic names ({order_id}_{artifact}.{ext}), and don't pass carrier URLs where a file upload is expected.
Duplicate or reordered webhooks create two packages. Confirm the unique constraint on event ID and make the worker check the current dispute state before acting. Never trust arrival order.
Submission is skipped as "wrong state". A newer webhook has already moved the dispute. Re-read the state from Klarna and let the worker follow it.
You now have a pipeline that accepts Klarna dispute webhooks idempotently, classifies INR and Significant Deviation cases, assembles evidence into a single schema, enforces POD eligibility as a hard gate, and submits ahead of an internal deadline with typed retries and a stored validation report.
Next steps, in rough order of value: add a second carrier adapter to find the gaps in your schema, build a manual review queue with the validation report attached, extend the router to other Klarna dispute reasons, and track win rate by rule failure to tune thresholds.
Maintaining all of this has a running cost: carrier APIs change, Klarna's evidence rules change, and thresholds need re-checking. If you'd rather not own that surface, Guzco runs the same workflow as a managed service. It builds evidence to Klarna's POD spec, monitors deadlines in real time, and reports zero missed deadlines this year on its Klarna solution page, so disputes don't reach your team.