WeChat Mini Programs Can't Identify a Phone. This Team Built the Closest Workable Substitute
Preface
Background first. Our team maintains a two-platform product, with PC and Mini Program sharing the same login system. The product recently raised a requirement: login requests should carry a device identifier, used for device-dimension analysis — how many accounts a device has been associated with, and whether a login came from an unfamiliar environment.
One sentence in the requirements document was killer: after users clear cache, delete the Mini Program and reinstall it, the backend should still recognize it as the same phone.
This sentence cannot be implemented in WeChat. Mini Programs can't get IMEI, can't get MAC, and have no IDFA or Android ID. A step back, self-generating a UUID and writing it to Storage disappears when cache is cleared. Worse, WeChat's Storage is isolated by "WeChat user × Mini Program"; log in with a different WeChat account and the previous user's data can't be read at all.
We wrote the research conclusion on the first page of the design document: a pure client implementation cannot produce an identifier that proves physical device identity. But the requirement couldn't just be bounced back, so we reframed it. Not "who is this phone", but "this WeChat user has logged in on a device like this". WeChat offers no answer to the first question; the second can be computed.
This article only discusses the client-side design of the identifier. Device lists, session revocation, how the backend stores and uses it, are all out of scope. It follows the order of decisions at the time, including approaches tried and abandoned.
Problem decomposition
Three things on the login path
Initially we wanted to solve everything with one field; the review showed that wouldn't work. At least three unrelated things are on the login path.
One is who is logging in — the same WeChat user, or the same account.
One is what the current environment looks like, used to generate a repeatedly computable identifier.
One is whether this login is trustworthy, used to identify abnormal environments and decide whether to strengthen verification.
Stuffing three things into one field means someone will inevitably use it for the other thing after launch. So on day one of the design, we drew the line: risk judgement continues to use the token returned by Alibaba Cloud risk control SDK. It's a query credential valid for roughly ten minutes, can be different every time, and was never a device ID. The session key only participates in request signing; it doesn't enter the hash input, nor does it land in Storage or logs.
The new deviceId only answers the second question. But it isn't a pure environment description; the answer also carries "who". This is a deliberate trade-off, with a cost described later.
What the existing identifiers are doing
The project already had several similar things, and reviewers asked several times why not just reuse them.
One is a machine ID with no prefix, generated as a UUID on first launch and written to Storage, retained on logout, used for telemetry and cloud metadata. One is a channel ID starting with mp_, used by the endpoint-cloud collaboration channel SDK, also reported as X-Socket-Device-Id in login requests. Then there's the short-term token from Alibaba Cloud risk control SDK and the session key issued after login — one goes in the request header, one participates in signing.
None of these are device IDs, and none should be pulled into the new algorithm. The first two identify "this installation", change when cache is cleared, and directly conflict with the new requirement. The latter two are credentials; semantically they have no place in a long-lived identifier. The final rule: the new value doesn't read them, doesn't concatenate them, doesn't hash them, and doesn't fall back to them on failure.
Approach ideas
What each candidate identifies
The research phase produced a table. The interesting thing: every row looks like a device ID, but looking carefully, no row actually identifies a phone.
| Approach | What it actually identifies | Conclusion |
|---|---|---|
openid |
The same WeChat user's identity in this Mini Program | Can't be a device ID alone; kept as the user factor of deviceId |
unionid |
The WeChat user under the same open-platform entity | Not used; this scenario only needs the user dimension within the Mini Program |
| UUID in Storage | This installation | Not used; changes on cache clear and reinstall |
| Device info feature hash | Platform, brand, model, chip, memory tier | Can't be a device ID alone; same models collide at scale; kept as the device factor |
| Alibaba Cloud risk control SDK short-term token | One query credential | Not part of computation; continues in the risk request header |
| Third-party device security service | Server-side device ID | Not used; client can't recompute, semantics also wrong |
The first two rows and the last row died fast. The real deliberation was between Storage UUID and feature hash. The former has great uniqueness, but its lifecycle is a single installation, directly opposed to "unchanged after reinstall". The latter has a long enough lifecycle, but its discrimination depends entirely on model distribution, which wasn't quantified at the time.
Also one fork discussed: the feature hash could be computed only on the client, letting the backend use the openid already in the request to concatenate (openid, feature hash). The collision scope would be identical to client-side computation, and the client would save one call to fetch openid.
We didn't go this route. Login, refresh, and SDK reporting paths need to carry the same self-contained string. There are multiple backend services; expecting each to assemble it itself means one assembly error and values won't match, and such errors are hard to find during integration testing. So we decided to compute the full value on the client and pass it through verbatim on every path.
Collisions must be calculated first
Using device features alone, collision scale is determined by model distribution. On iOS, cpuType isn't available, and memory for the same model is fixed, so all iPhones of the same model share the same value.
This consequence isn't theoretical. The backend doing device management with it will merge different users' devices into one. Risk control counting "how many accounts one device is associated with" will flag entire batches of same-model users. Once such false positives ship, the investigation cost is higher than rebuilding the algorithm, so it must be worked out at the design stage.
Adding openid, the collision scope shrinks as follows.
| Scenario | Device features only | Device features + openid |
|---|---|---|
| Different WeChat users, same model device | Collision | No collision |
| Same WeChat user, two same-model devices | Collision | Still collision |
| Same WeChat user, two same-configuration Macs | Collision | Still collision |
| Same phone, different WeChat account | N/A | Value differs |
The fourth row has an additional reason. Storage is isolated by user; after switching accounts, the new user can't read the old user's cache, and openid also differs, so the value necessarily differs.
So the explanation to the backend can only be one sentence: deviceId means "WeChat user × model, chip, and memory tier". Two same-model devices under the same username will merge; if the backend kicks a session by this value, both get kicked. Associating the same physical device across WeChat accounts remains the risk control path's job.
Product copy also went through a round of changes. Uniformly use "login device" or "login session", not "uniquely identifies this phone". This change looks light, but it's the only honest external expression of this algorithm.
Implementation
The whitelist was tested on four real devices
The field whitelist didn't copy the official docs. The types, field names, and platform coverage in the docs don't match real devices. On November 16, 2026, we gathered four machines and read field by field; the whitelist was trimmed to actual measurement results.
| Field | Honor SER-AN00 (Android 16) | Xiaomi 24129PN74C (Android 16) | iPhone 14 (iOS 17.6) | Mac16,7 (macOS 15.7.4) |
|---|---|---|---|---|
platform |
android |
android |
ios |
mac |
brand |
HONOR |
Xiaomi |
iPhone |
apple |
model |
SER-AN00 |
24129PN74C |
iPhone 14<iPhone14,7> |
Mac16,7 |
| CPU | cpuType: MT6899 |
cpuType: unknown |
No such field | Field name is CPUType, value Apple M4 Pro |
memorySize |
11473 |
15113 |
5669 |
49152 |
Normalized result (without openid) |
android / honor / ser-an00 / mt6899 / 12 |
android / xiaomi / 24129pn74c / - / 15 |
ios / iphone / iphone14,7 / - / 6 |
mac / apple / mac16,7 / apple m4 pro / 48 |
After running those four machines, the whitelist changed in five places, each only discoverable through real-device testing.
First is memorySize. The docs say string, in MB; all four real devices returned numbers. Values are lower than nominal memory; the 12GB Honor reports 11473. The iPhone 14 reports 5669; divided by 1024 gives 5.54, right at the rounding boundary.
If we used rounding, a minor system version upgrade making the kernel hold a few dozen more MB would drop 5669 below 5500, becoming 5, and the value drifts. Since reported values tend to be low, the fractional part is usually a distance from the next integer edge, and small drift won't change the result; we uniformly round up to GB. 11473 gives 12, 15113 gives 15, 5669 gives 6, 49152 gives 48. Both string and number types are accepted, avoiding silent errors if a platform switches back to strings.
Second is the Mac CPU field name. On phones it's cpuType; on Mac it's uppercase CPUType. Reading only lowercase, Mac always falls to -. You can't find this trap without real-device testing; the code ends up as deviceInfo.cpuType ?? deviceInfo.CPUType, reading both.
Third is the literal unknown. Xiaomi's cpuType is the string unknown; new models' model can also be unknown at launch. Both are normalized to -, with no special treatment.
Fourth is iOS's model. Its form is iPhone 14<iPhone14,7>; outside the angle brackets is the marketing name maintained by WeChat, which changes until new devices are adapted. When the content inside the brackets is non-empty, only the hardware identifier inside is taken, then normalized, yielding iphone14,7. Mac's model is itself Mac16,7, no brackets; the whole string is normalized.
Fifth is deleting fields. deviceAbi was removed; all three devices with values report arm64-v8a, no discrimination. abi also can't be used; officially it's the binary interface of the WeChat package itself; if WeChat switches to 32-bit or reinstalls a package of a different architecture, it changes.
A batch of fields was excluded from the start. System version, WeChat version, SDK version, app version upgrade too frequently, turning a device ID into a byproduct of version numbers. benchmarkLevel stopped being maintained from base library 3.4.5; some devices return -1 directly. Language, timezone, network type, IP are environment-variable or sensitive. Identity fields like phone number and account ID, except openid, are never mixed in.
openid itself only gets trimmed, case unchanged. It's case-sensitive; lowercasing would collide different users into the same value, and such errors are hard to trace later online.
Four devices plus the same test openid yield four different values. Collision of two same-model devices isn't yet tested; that's one item in the todo list.
Normalization and digest
Algorithm version is acf-v1. Field order is fixed, missing values write -, not removing a field from the string because it's unreadable. Object key traversal order, or whether the platform returns null or undefined for empty values, shouldn't make the digest jitter.
const canonical = [
'acf-v1',
`openid=${openid.trim()}`,
`platform=${normalize(deviceInfo.platform)}`,
`brand=${normalize(deviceInfo.brand)}`,
`model=${normalizeModel(deviceInfo.model)}`,
`cpuType=${normalize(deviceInfo.cpuType ?? deviceInfo.CPUType)}`,
`memoryGb=${normalizeMemoryGb(deviceInfo.memorySize)}`,
].join('|');
const deviceId = `acf-v1_${toBase64Url(sha256(toUtf8Bytes(canonical)))}`;
Three normalization functions roughly look like this; the logic isn't complex, the pain is in the edges.
const normalize = (value: unknown): string => {
const s = String(value ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
return s === '' || s === 'unknown' ? '-' : s;
};
const normalizeModel = (value: unknown): string => {
const matched = String(value ?? '').match(/<([^<>]+)>/);
return normalize(matched ? matched[1] : String(value ?? ''));
};
const normalizeMemoryGb = (value: unknown): string => {
const n = typeof value === 'string' ? Number(value.trim()) : value;
if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0) return '-';
return String(Math.ceil(n / 1024));
};
normalize's rules are plain: string conversion, trim, lowercase, collapse consecutive whitespace into one space. Empty or unknown outputs -. These rules can't apply to openid, for the reason above. normalizeModel adds a bracket-extraction step; normalizeMemoryGb adds type compatibility and round-up; the rest of the checks are defensive — better to output - than let an invalid value skew the whole digest.
The value shape is acf-v1_ plus 43 characters of unpadded base64url, 50 bytes total. Login protocol allows 64 bytes and charset [0-9A-Za-z_-], right in bounds.
The digest algorithm has a version constraint here too. The SDK originally had no SHA-256 dependency; iOS 13's JSCore has no BigInt, and common third-party libraries can't run directly. When integrating the Alibaba Cloud risk control SDK for request signing, we'd already written a BigInt-free implementation; we extracted its SHA-256 and UTF-8 encoding, moved them into the SDK's async subpackage, and added base64url encoding. The main package only keeps an in-memory snapshot, serial queue, and request-header assembly; digest code doesn't enter the main package, avoiding slowing Mini Program startup.
The boundary of SHA-256's role here should be clear. openid's entropy is high enough that a third party holding only deviceId can't enumerate back to the original text. But a backend holding openid can enumerate the features in a tiny "model × chip × memory tier" space. The hash doesn't provide anonymization, doesn't add uniqueness, has no anti-forgery power; anyone with the same input can compute it again. Its role here is only compressing a readable feature string into a fixed-length string.
Change the whitelist or normalization rules and open a new version, without touching the semantics of acf-v1 already issued. The rules were revised against four machines before launch, but version remains v1 because it's never been issued externally.
Why screen parameters aren't collected this version
getWindowInfo()'s returned width, height, pixel ratio were planned for the first version. The call is synchronous, supported since base library 2.20.1, essentially zero cost.
The case for keeping them was plausible. Display size, zoom, resolution — most people set them once and don't touch. Plus within the cache period the value is frozen; the value can only drift when "changed display settings" and "cleared cache or reinstalled" happen together. When a new model's model is still unknown, several un-adopted devices under the same username have only brand, chip, and memory to tell apart; on Android, screen heights like 813 vs 806 could actually separate them.
Ultimately not collected, with reasons more concrete each time.
Same-model screens are identical anyway; adding them leaves current collision scope almost unchanged, essentially collecting for nothing. iPhone screens are entirely determined by model; iPhone 14 is always 390×844@3, no gain. The 414×780 measured on Mac matches safeArea's width and height — that's the Mini Program window size; once the host enables draggable windows, it changes as users drag the window, and PC can never use it. Four machines already show large variance across platforms; with no clear benefit, don't expand the whitelist.
Re-evaluation conditions were also written into the doc. If collision of devices with model as - under the same username grows too large to ignore, or HarmonyOS real-device discrimination is clearly insufficient, come back and recalculate.
If added, only on the Mini Program mobile side; PC writes fixed -. Width and height rounded, sorted with the smaller first, eliminating portrait/landscape swaps; DPR kept to three decimal places, output as <min>x<max>@<dpr>.
This change alters the input string, so it must bump to acf-v2. Launched users have acf-v1_… in cache; format mismatch treats it as missing and regenerates, and the backend sees a batch of "new login devices". So activation requires a sync with the backend first.
Cache strategy: compute once, freeze
Computing the digest once isn't expensive, but there's no need to compute every cold start. After generation, write to Storage; next time read directly. All reads/writes use async interfaces; write in-memory snapshot first, then to disk; disk-write failure doesn't break this login; next cold start recomputes as cache-miss.
Once cache hits, the value is frozen. Later device changes don't recompute the cached deviceId.
The following changes only enter a new value after cache clear, reinstall, or algorithm upgrade regenerates it.
- WeChat adapts a new model from
unknownto the real model; un-adopted models under the same username share- cpuTypechanges fromunknownto a real chip name- Base library crosses 2.29.0 or 2.30.0, previously unreadable fields start having values
- System upgrade changes kernel reserved memory,
memorySizecrosses a GB integer boundary; round-up only happens when the reported value exactly crosses an integer
acf-v1 doesn't read screen or window; portrait/landscape, split-screen, foldable open/close, dragging windows on PC, none affect this value.
So "value unchanged after cache clear or reinstall" has prerequisites. Only if the same real openid is still obtainable and none of the features above changed does it hold. When the new value differs from the old, the backend treats it as a new login device; the client doesn't use that difference to judge abnormal login. This is also written in the handover notes to the backend.
Login can't be held up by a device identifier
First login without cache has to get openid first. The flow is wx.login for a one-time code, then a request to an endpoint that only does jscode2session to exchange it. This endpoint doesn't log in, doesn't create accounts, carries a fixed product-code Header, doesn't guess the product from User-Agent; success condition is HTTP 2xx and platform wrapping code === 0.
A hard constraint: any failure in the device-identifier path must not interrupt login.
Each attempt gets a 3-second cap, covering queue-lock wait, wx.login, and this HTTP. Timeout, no code, HTTP or platform error, empty openid, rate-limiting all count as one failure. Same process accumulates at most 2; worst case login path waits 6 seconds.
At startup, the SDK pre-fetches in the background. Pre-fetch failure doesn't generate a fallback value; left to the login path to handle. If pre-fetch is still running when the user starts login, login queues behind it, reusing the same result. If deviceId cache exists, or openid cache exists, login doesn't wait on network at all.
Two failures, and the login path generates a one-time fallback seed: character o plus 27 random characters, 28 total, shape close to common Mini Program openid, but that's empirical shape, not official spec. Seed isn't persisted. Computed value uses a different prefix, acf-v1-tmp_ plus 43 chars, 54 bytes total, still within protocol. Backend recognizes this prefix and treats it as a temporary device.
Fallback value is written to Storage. While cache exists, subsequent cold starts reuse it directly, not overwritten by openid later successfully fetched. Only after clearing Storage does pre-fetch rerun; if it fails again, a new fallback value.
Random source prefers crypto.getRandomValues, falls back to Math.random. The seed only needs low collision, not a security credential; unusable random source can't fail login either.
The other abnormal branches are handled the same. getDeviceInfo() throwing is treated as an empty object, all fields -, still computed. Missing config, async subpackage load failure, compute errors: the issuing request goes out as normal, just without the Header; one console.error line.
wx.login's code can only be consumed once
This section is where implementation time really went.
The code from wx.login can only be consumed successfully once. Two calls at the same moment may get the same code; whoever consumes it first causes the other to receive 40029 or 40163. Three places in the SDK call wx.login: exchanging openid, intranet entry visibility probe, WeChat login ticket verification; they step on each other concurrently.
Eventually these three share one lock. The lock only wraps wx.login itself; requests after getting the code run outside the lock with their own timeout, so slow requests don't hold the lock or get misjudged as failed by the lock's timeout.
A more subtle problem: waiting for the lock times out, this attempt is abandoned, but the inner one is still queued. If left unchecked, it later gets the lock and fires another wx.login, producing an unconsumed code that might also knock out someone else's. So on abandonment, set a flag; on acquiring the lock, skip the call directly, and don't consume the returned wx.login.
The cost is in the acceptance list. After mutual avoidance with the intranet entry code exchange, the intranet entry sometimes appears a round late, and the cold-start probe occasionally gives "inconclusive", needing a re-probe when the login panel opens. We judged this acceptable because the entry only appears late, never disappears.
UI waiting was also handled. Clicking WeChat, enterprise entry, or email collapses the panel and shows "Logging in", covering that wait. Phone-number entry waits for the authorization popup before collapsing the panel, so adds another "Logging in" before the popup; repeated clicks during the wait are ignored.
The 6-second cap exists so the first login carries a device identifier whenever possible. It changed the team's prior convention of "auth requests don't wait on background tasks"; reviewers objected. After explaining the cap and failure fallback, the plan passed.
Boundaries and acceptance
What this value can't be used for
- Can't be a permanent physical device ID. While cache exists it doesn't change; after clearing, whether it computes back depends on whether
openidand the features are still the same - Can't judge two logins as the same phone across WeChat accounts; after switching accounts the value differs — that's the cost of including
openid - Can't judge on the client whether two installations are the same physical phone; two same-model devices of the same user can have the same value
- No logs, no telemetry, no ad attribution, no cross-product tracking; it can link to a person, reported only on auth and risk control paths
- Doesn't replace risk control; cross-account device association still uses Alibaba Cloud risk control SDK's token
After the value is computed, someone must use it. The login issuing request carries the Header; after successful login, report device activity asynchronously once; cold start after login reports once; back to foreground reports once. These are fire-and-forget; failures just log a warn, no retry, no impact on login result.
Where "is this login trustworthy" actually needs judging remains on the Alibaba Cloud risk control SDK request headers.
The channel ID is also reported. Originally generated by the channel SDK after successful login, it doesn't exist on a new device's first login, so the host generates and writes it before issuing; the channel SDK later gets the same value. The SDK only passes through, doesn't participate in computation; if unavailable, sends empty string, login continues.
Two things persist locally long-term: real openid and deviceId, both not cleared on logout, only invalidated by cache clear, reinstall, or WeChat account switch. Brand, model, chip, memory tier plus openid, plus this persistence method, whether still in the privacy statement's scope, needs separate confirmation. Out of scope, change the whitelist and bump the algorithm version.
What's not yet fully tested
Document status is still Draft. Two Android, one iOS, one Mac in the whitelist. These remain open:
- Windows: what
modellooks like, whether the CPU field iscpuTypeorCPUType, whethermemorySizeis a number - HarmonyOS phones and HarmonyOS PC, the same set of questions
- Two same-model real devices, confirm same-user collision and different-user no collision
- Multiple cold starts on one device and across system upgrades, whether
memorySizecrosses the GB integer boundary by itself - For new models not yet adapted by WeChat, whether iOS
modelstill has angle brackets
Developer tool return values can't be treated as real devices. Before these are filled in, don't claim externally the algorithm covers all platforms.
Summary
The approach lands on a rather unglamorous conclusion. WeChat Mini Programs can't give a physical device ID; what we can make is a recomputable "user × device features" identifier, whose recomputability after cache clear and reinstall depends on whether openid and these features all stay unchanged.
The time in practice isn't spent on hashing; it's two things. One is testing the field whitelist device by device; the mismatches between docs and real devices were more than expected. The other is holding the "don't interrupt login" line; fallback, degradation, timeout, locking, each point bends toward this direction.
A reminder: this value can only serve as the identifier for login devices and login sessions. If product or security policy requires high-confidence identification of the same physical device, this layer isn't enough; the server must combine account, risk services, and additional verification.