Skip to content

Commit e6a2613

Browse files
committed
Handle Unicode characters
1 parent a855e9a commit e6a2613

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

src/index.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import type {
2424
OnStatus,
2525
OnStatusArgs
2626
} from "./emitters";
27+
import { escapeUnicode } from "./utils";
2728

2829
/**
2930
* The main API Class
@@ -730,7 +731,7 @@ export default class WhatsAppAPI {
730731
["sign", "verify"]
731732
);
732733

733-
const data = encoder.encode(raw_body);
734+
const data = encoder.encode(escapeUnicode(raw_body));
734735
const result = await this.subtle.sign("HMAC", key, data.buffer);
735736
const result_array = Array.from(new Uint8Array(result));
736737

src/utils.ts

+7
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@ export function isInteger(n: unknown): n is number {
44
return Number.isInteger(n);
55
}
66

7+
export function escapeUnicode(str: string) {
8+
// https://stackoverflow.com/a/40558081
9+
return str.replace(/[^\0-~]/g, (ch) => {
10+
return "\\u" + ("000" + ch.charCodeAt(0).toString(16)).slice(-4);
11+
});
12+
}
13+
714
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
815
export type XOR<T, U> = T | U extends object
916
? (Without<T, U> & U) | (Without<U, T> & T)

test/index.test.cjs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1520,9 +1520,9 @@ describe("WhatsAppAPI", function () {
15201520
const phoneID = "1";
15211521
const user = "2";
15221522
const body =
1523-
"Let's pretend this body is equal to the message object";
1523+
"Let's pretend this body is equal to the message object and can handle unicode characters like みどりいろ and J'ai mangé des pâtes";
15241524
const signature =
1525-
"sha256=8d2c8fd74d3ac31eafd99563ac39107a45e5ea1d44831e291353193729d57f56";
1525+
"sha256=0363007aabdf1ab579f35936651a460fb5fa1aaf40df98b1264446b72cc96688";
15261526

15271527
const name = "name";
15281528
const message = {

0 commit comments

Comments
 (0)