Import from costco.com
Check your Costco receipts from the last 30 days at once. Free, no sign-up.
Import all your receipts at once
On a computer, a bookmark you click on costco.com checks every warehouse receipt from the last 30 days in one go.
- Drag this button to your browser’s bookmarks bar: Import Costco receipts
- Sign in at costco.com and open Orders & Purchases.
- Click the bookmark. A new tab opens here with what you’re owed.
What it reads, and what it doesn’t
It runs in your browser on costco.com. Your Costco password and login never leave your browser: the bookmark uses them only to ask Costco’s own website for your receipts, as the Orders & Purchases page does.
Only store, date, item numbers and prices are passed to this site, with short item names and the receipt’s transaction number. Never your membership number, card, address or the receipt’s barcode. They travel in the address of the page it opens, after a “#”, which browsers don’t send to a server; this page sends on only the numbers, to check them.
Nothing is kept unless you give an email address to watch the receipts for 30 days; then only the receipts’ numbers are kept, as for any receipt you ask us to watch.
Costco can change its website at any time, and the bookmark may then stop working until it is updated here. It is not made or endorsed by Costco. Version 1.
Read the bookmark’s code
// "Import from costco.com": the bookmarklet's source (docs/receipt-import.md).
//
// Run on a signed-in costco.com page, it asks Costco's own orders endpoint, from that page, for the
// member's warehouse receipts of the last 30 days, keeps only store, date, transaction number and
// per item: item number, a short name, quantity, unit price and instant savings, and opens
// couponpriceadjustment.com/import with that in the address's fragment (never sent to a server).
// The member's Costco login token is read from the page and used only in the request to Costco;
// it is never put in the payload, shown, or sent anywhere else.
//
// The page's link is this file with comment lines dropped and lines joined (lib/import-bookmarklet.ts
// bookmarkletHref); tests/import/bookmarklet.test.ts runs that exact link's code. So: every
// statement ends with a semicolon, comments are whole lines starting with //, and no line may end
// inside a string.
void (function () {
var V = 1;
var SITE = 'https://www.couponpriceadjustment.com/import#d=';
var API = 'https://ecom-api.costco.com/ebusiness/order/v1/orders/graphql';
var DAYS = 30;
var MAX_RECEIPTS = 40;
var tab = null;
function Fail(reason, words) {
this.reason = reason;
this.words = words;
}
function say(f) {
if (tab) {
try { tab.close(); } catch { }
}
alert(f.words + '\n\n(Costco import v' + V + ': ' + f.reason + ')');
}
function pad(n) {
return (n < 10 ? '0' : '') + n;
}
function us(d) {
return pad(d.getMonth() + 1) + '/' + pad(d.getDate()) + '/' + d.getFullYear();
}
// A stored value: the token itself, a JSON string of it, or an object holding it in "secret"
function unwrap(v) {
if (!v) return '';
var s = String(v).trim();
if (s.charAt(0) === '"' || s.charAt(0) === '{') {
try {
var o = JSON.parse(s);
s = typeof o === 'string' ? o : (o && (o.secret || o.idToken || o.token)) || '';
} catch { }
}
return String(s).trim();
}
function stores() {
var out = [];
try { out.push(localStorage); } catch { }
try { out.push(sessionStorage); } catch { }
return out;
}
function first(names, test) {
var all = stores();
for (var i = 0; i < all.length; i++) {
for (var j = 0; j < names.length; j++) {
var v = unwrap(all[i].getItem(names[j]));
if (v && test(v)) return v;
}
}
return '';
}
function looksLikeToken(v) {
return /^[\w-]+\.[\w-]+\.[\w-]+$/.test(v) && v.length > 100;
}
function findToken() {
var t = first(['idToken', 'id_token', 'IdToken'], looksLikeToken);
if (t) return t;
var all = stores();
for (var i = 0; i < all.length; i++) {
for (var k = 0; k < all[i].length; k++) {
var key = all[i].key(k);
if (key && /id_?token/i.test(key)) {
var v = unwrap(all[i].getItem(key));
if (looksLikeToken(v)) return v;
}
}
}
return '';
}
function findClientId() {
return first(['clientID', 'clientId', 'client_id', 'wcsClientId'], function (v) { return /^[\w-]{8,80}$/.test(v); });
}
function query(full) {
var to = new Date();
var from = new Date(to.getTime() - DAYS * 86400000);
var fields = 'warehouseNumber transactionDate transactionDateTime registerNumber transactionNumber instantSavings ' +
(full ? 'receiptType documentType transactionType ' : '') +
'itemArray { itemNumber itemDescription01 itemDescription02 unit amount itemUnitPriceAmount }';
return '{ receiptsWithCounts(startDate: "' + us(from) + '", endDate: "' + us(to) +
'", documentType: "all", documentSubType: "all") { receipts { ' + fields + ' } } }';
}
function ask(token, clientId, full) {
return fetch(API, {
method: 'POST',
headers: {
'Content-Type': 'application/json-patch+json',
'costco.service': 'restOrders',
'costco.env': 'ecom',
'costco-x-authorization': 'Bearer ' + token,
'costco-x-wcs-clientid': clientId,
'client-identifier': '481b1aec-aa3b-454b-b81b-48187e28f205'
},
body: JSON.stringify({ query: query(full) })
}).then(function (res) {
if (!res.ok) {
throw new Fail('Costco answered ' + res.status, res.status === 401 || res.status === 403
? 'Costco did not accept the sign-in. Sign in to costco.com again, then click the bookmark.'
: 'Costco did not answer as expected. Try again later.');
}
return res.json().catch(function () {
throw new Fail('the answer was not JSON', 'Costco did not answer as expected. Try again later.');
});
});
}
// A GraphQL error's own words, with anything long or number-like taken out
function errorWords(body) {
var m = body && body.errors && body.errors[0] && body.errors[0].message;
return String(m || 'unknown').replace(/[\w.-]{20,}/g, '...').replace(/\d{5,}/g, '...').slice(0, 80);
}
function money(n) {
return Math.round(Number(n) * 100) / 100;
}
function isoDate(r) {
var s = String(r.transactionDate || r.transactionDateTime || '');
var m = s.match(/^(\d{4})-(\d{2})-(\d{2})/);
if (m) return m[1] + '-' + m[2] + '-' + m[3];
m = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/);
return m ? m[3] + '-' + pad(Number(m[1])) + '-' + pad(Number(m[2])) : '';
}
function shortName(s) {
return String(s || '').replace(/[^A-Za-z0-9 .,'&%#()+*-]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 30);
}
var FUEL = /gas|fuel|car ?wash|propane/i;
// One receipt as the payload keeps it, or null to leave it out (gas, car wash, no items bought)
function toReceipt(r) {
if (FUEL.test([r.receiptType, r.documentType, r.transactionType].join(' '))) return null;
var warehouse = String(r.warehouseNumber || '').replace(/^0+/, '');
var date = isoDate(r);
if (!/^\d{1,5}$/.test(warehouse) || !date) return null;
var items = [];
var list = r.itemArray || [];
for (var i = 0; i < list.length; i++) {
var it = list[i];
var amount = Number(it.amount);
var unit = Number(it.unit);
var d1 = String(it.itemDescription01 || '');
var slash = d1.match(/^\s*\/\s*(\S+)/);
if (amount < 0 && slash) {
// An instant savings line, printed on paper as "399702 /1775302 3.00-": its description
// names the item (or the start of its name) it belongs to; else the line above
var target = null;
for (var j = items.length - 1; j >= 0; j--) {
if (items[j].item === slash[1]) { target = items[j]; break; }
}
if (!target && !/^\d+$/.test(slash[1])) target = items[items.length - 1] || null;
if (target) target.instant_savings = money((target.instant_savings || 0) - amount);
continue;
}
// Returns, voids, zero lines, fees tied to an item ("EE/4164501") and fuel are not checked
if (!(amount > 0) || !(unit > 0) || d1.indexOf('/') >= 0 || /^(UNLEADED|PREMIUM|DIESEL|REGULAR)\b/i.test(d1)) continue;
var whole = unit === Math.floor(unit);
var price = Number(it.itemUnitPriceAmount);
items.push({
item: String(it.itemNumber).replace(/\D/g, ''),
name: shortName(d1),
quantity: whole ? unit : 1,
price: money(whole && price > 0 ? price : whole ? amount / unit : amount)
});
}
var ok = [];
for (var k = 0; k < items.length; k++) {
if (items[k].item) ok.push(items[k]);
}
if (!ok.length) return null;
var out = { warehouse: warehouse, date: date, items: ok };
var trn = String(r.transactionNumber || '').replace(/\D/g, '').replace(/^0+(?=\d)/, '');
if (trn) out.transaction = trn;
return out;
}
function encode(payload) {
return btoa(unescape(encodeURIComponent(JSON.stringify(payload))));
}
function run() {
if (!/(^|\.)costco\.com$/i.test(location.hostname)) {
throw new Fail('not on costco.com', 'Open costco.com and sign in, then click this bookmark again.');
}
var token = findToken();
if (!token) throw new Fail('no sign-in found', 'Sign in to costco.com first, then click this bookmark again.');
var clientId = findClientId();
if (!clientId) {
throw new Fail('no client id found', 'Open Orders & Purchases on costco.com, then click this bookmark again.');
}
// Opened now, while the click still counts, so the browser doesn't block it as a pop-up
tab = window.open('about:blank', '_blank');
if (tab) {
try {
tab.opener = null;
tab.document.title = 'Reading your receipts';
tab.document.body.textContent = 'Reading your receipts from costco.com...';
} catch { }
}
return ask(token, clientId, true).then(function (body) {
// A field this version asks for that Costco doesn't have: ask again with the fields seen in use
if (body && body.errors && body.errors.length) return ask(token, clientId, false);
return body;
}).then(function (body) {
if (body && body.errors && body.errors.length) {
throw new Fail('Costco answered with an error: ' + errorWords(body), 'Costco did not answer as expected. Try again later.');
}
var found = body && body.data && body.data.receiptsWithCounts && body.data.receiptsWithCounts.receipts;
if (!found) throw new Fail('the answer had no receipt list', 'Costco did not answer as expected. Try again later.');
var receipts = [];
for (var i = 0; i < found.length && receipts.length < MAX_RECEIPTS; i++) {
var r = toReceipt(found[i]);
if (r) receipts.push(r);
}
if (!receipts.length) {
throw new Fail('no warehouse receipts in the answer', 'No warehouse receipts from the last ' + DAYS + ' days were found on costco.com.');
}
var url = SITE + encode({ v: V, receipts: receipts });
if (tab) tab.location.href = url;
else location.href = url;
});
}
// run() itself up to window.open, in the click's own turn; what it throws or rejects is said once
var started;
try {
started = Promise.resolve(run());
} catch (e) {
started = Promise.reject(e);
}
started.catch(function (e) {
say(e instanceof Fail ? e : new Fail('blocked by the page (' + ((e && e.name) || 'error') + ')',
'The import could not reach Costco from this page.'));
});
})();