I am using the whatsapp api with webhooks, however I can't receive my message when I write in the chat.
This is my code, in my number I get my country code (MX) and my phone number from whatsapp: e.g. 521xxxxxxxxxx, but add a '1' after my country code and before my phone number and I don't get the message:
app.post("/webhook", (req, res) => {
let body = req.body;
console.log(JSON.stringify(req.body, null, 2));
if (req.body.object) {
if (
req.body.entry &&
req.body.entry[0].changes &&
req.body.entry[0].changes[0] &&
req.body.entry[0].changes[0].value.messages &&
req.body.entry[0].changes[0].value.messages[0]
) {
let phone_number_id =
req.body.entry[0].changes[0].value.metadata.phone_number_id;
let from = req.body.entry[0].changes[0].value.messages[0].from;
let msg_body = req.body.entry[0].changes[0].value.messages[0].text.body;the message text from the webhook payload
axios({
method: "POST",
url:
"https://graph.facebook.com/v12.0/" +
phone_number_id +
"/messages?access_token=" +
token,
data: {
messaging_product: "whatsapp",
to: from,//------------------>521(phone_number)
text: { body: "Ack: " + msg_body },
},
headers: { "Content-Type": "application/json" },
}).catch((error)=>{console.log(error)});
}
res.sendStatus(200);
} else {
res.sendStatus(404);
}
});
I receive this:
[AxiosError: Request failed with status code 400] {
message: 'Request failed with status code 400',
name: 'AxiosError',
code: 'ERR_BAD_REQUEST',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'User-Agent': 'axios/0.27.2',
'Content-Length': 79
},
method: 'post',
url: 'https://graph.facebook.com/v12.0/number/messages?access_token=Mytoken',
data: '{"messaging_product":"whatsapp","to":"521xxxxxxxxxx","text":{"body":"Ack: ' +
'dc"}}'
},
request: ClientRequest {
_events: [Object: null prototype] {
socket: [Function],
abort: [Function],
aborted: [Function],
connect: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'graph.facebook.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 95,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
connection: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'graph.facebook.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 95,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
_header: 'POST ' +
'/v12.0/number/messages?access_token=Mytoken' +
'HTTP/1.1\r' +
'\nAccept: application/json, text/plain, */*\r' +
'\nContent-Type: application/json\r' +
'\nUser-Agent: axios/0.27.2\r' +
'\nContent-Length: 79\r' +
'\nHost: graph.facebook.com\r' +
'\nConnection: close\r' +
'\n\r' +
'\n',
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object]
},
socketPath: undefined,
method: 'POST',
path: '/v12.0/number/messages?access_token=Mytoken',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
socket: [TLSSocket],
connection: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 400,
statusMessage: 'Bad Request',
client: [TLSSocket],
_consuming: true,
_dumped: false,
req: [Circular],
responseUrl: 'https://graph.facebook.com/v12.0/number/messages?access_token=Mytoken',
redirects: []
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 79,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl: 'https://graph.facebook.com/v12.0/number/messages?access_token=Mytoken'
},
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object: null prototype] {
accept: [Array],
'content-type': [Array],
'user-agent': [Array],
'content-length': [Array],
host: [Array]
}
},
response: {
status: 400,
statusText: 'Bad Request',
headers: {
'set-cookie': [Array],
vary: 'Origin, Accept-Encoding',
'x-business-use-case-usage': '{"WhatsApp_Business_id":[{"type":"whatsapp","call_count":1,"total_cputime":1,"total_time":1,"estimated_time_to_regain_access":0}]}',
'content-type': 'application/json',
'www-authenticate': 'OAuth "Facebook Platform" "invalid_request" ' +
'"(#131030) Recipient phone number not in allowed ' +
'list"',
'access-control-allow-origin': '*',
'facebook-api-version': 'v19.0',
'strict-transport-security': 'max-age=15552000; preload',
pragma: 'no-cache',
'cache-control': 'no-store',
expires: 'Sat, 01 Jan 2000 00:00:00 GMT',
'x-fb-request-id': 'A4rSbxyIJNyOf4R5r1pPkmk',
'x-fb-trace-id': 'ATu77bL3PMb',
'x-fb-rev': '1011688366',
'x-stack': 'www',
'x-fb-debug': 'J+fSMhXGpY7EOvDPb+Bf0lGTUe/OgXwlySpC14MS0JNJL+eXFrmiELIAMBhVh8j36y0Q2vFDiXGZit2yNtrMoQ==',
date: 'Tue, 27 Feb 2024 21:00:29 GMT',
'transfer-encoding': 'chunked',
'proxy-status': 'http_request_error; ' +
'e_clientaddr="AcL58ZR0DI9KDOj5eMoVAZg-f5FwcwjY6s07lJ0LpyF4_wc6VZA1RkQaE2RfjTo_WT3AynbeCXCQI1j3gYHS3e_dZXuXC9HN5aaRumYFpu4EFy_1eQ"; ' +
'e_fb_vipport="AcK5ONstOkchBHFvIlZoDqmZfFKMwucd1XsGYo8bm86fqFA-o9UeBqQS3biH"; ' +
'e_upip="AcIGZA5ozrram3zvwHpdysfH2v-83JoYqAyPfTIrEC8vUCSqBckYNKEY8mx4mhKbMNAoCLhAXA52flp5NkhVTU188knAxP61wsg"; ' +
'e_fb_hostheader="AcLdwktEbpovXClbGu6IFN0K9tlmVCmCtKQ7DFFdGsOECLu_Bn7eY2_ukkczwJUkp2oQ8pB4k5y66lZV"; ' +
'e_fb_vipaddr="AcKN9Yn1EoXzBbv6WeC37NhCpQd8LBv2CE1yY8gyAMTiCjHihFd60TY5seJG3pK542-KSrO-xfK823JV1yWnwjIbtu0xTjO_rA"; ' +
'e_fb_requesthandler="AcI8WdQuUQBeJBsPjGIGnRjC0F61uqubD8JXORvjWtJyz0GftPNW7bbv_JJ8QYVFGetMscD6NBA"; ' +
'e_fb_builduser="AcKTd7iW4Ev_O8dt-w7A2Yi_rOhXnfNlqQwQQq03c4vVeiHmyBRcgta5jjjeSA58100"; ' +
'e_fb_binaryversion="AcLZ-iEQXpObJYssQTQdmbQh6JQLuIfsTweRqFa0K6OKpQ8q1yRVhLUFGuzw1n_8Zht9-g9MKYjuvVbw72t8xWA8OVqVUXEdDyM"; ' +
'e_proxy="AcLC3wcuh2BtM47AQXQvv8I9GzJvYlMx4160zHih8VdVVTZb4W5NFv2d0_LRjCW57Xc0uERkMb-GH7oT0HU", ' +
'http_request_error; ' +
'e_clientaddr="AcItFG-AcAHvymkWscj4syktDm371pYva2x46yxQCeDLI7PbHPDkzlcRDi6gYiGvGEWQ7_sSO6DCwLrIhQ"; ' +
'e_fb_vipport="AcJOtyZ7_bnfdk8N8-GKlFS6Iz13HEg9SmmHklUsg-4der1GLqYSQeII231g"; ' +
'e_upip="AcIJorrXD3SMBDdgp9-4SQyjrXVdPViOkc4YCbox4HsSIA-sqoybCEYsWkpxrJ4_2jSYpM1G1iE6GccdKXOJhoTzr81stbCIZQ"; ' +
'e_fb_hostheader="AcJXaW1xFHUWGb6s0v-AtUULyf_mOykVZ4iLwvdpzSYQBnQ_cKRYDI-eDNHR6HROSMQT4lQFldDZgT5w"; ' +
'e_fb_vipaddr="AcKz4dDMkcUhGTLcrGeyMHW2crcZvhpqwNu-hol3mpZSzMV0VUEqeqn7IdeNTL_YnyXqEA"; ' +
'e_fb_requesthandler="AcJ9zSgz_zrHT0tOmByndPZTqKYBQRPj6ziyFhPF-CU_RN_QlFbZTp4b6SJkjlv-A6Sskl6bau8"; ' +
'e_fb_builduser="AcLKeTVsLgi60eX1B5MtHQdQRIDUQiBh91JFX7L7xEDYqftu9eRKV0EGXz2IiJvLacs"; ' +
'e_fb_binaryversion="AcK4g_jOdwqfncbaMwKkRm-_0ueZv_eOvAB83pIto9MAVlE75bsfQEvXBfVYx8sOmmxZWqnAnSTbI8unHAa3wPdNdkI83KH6qTc"; ' +
'e_proxy="AcKxFOXFPi_6v5boo7PO0LnhyLqh2AAuiuhIX2Bef4cXmFuSzC_7X5Q3ZZwRmprXo6y3YYL9fVSdmB-Y"',
'alt-svc': 'h3=":443"; ma=86400',
connection: 'close'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: [Object],
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'https://graph.facebook.com/v12.0/number/messages?access_token=Mytoken',
data: '{"messaging_product":"whatsapp","to":"521xxxxxxxxxx","text":{"body":"Ack: ' +
'dc"}}'
},
request: ClientRequest {
_events: [Object],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
connection: [TLSSocket],
_header: 'POST ' +
'/v12.0/number/messages?access_token=Mytoken' +
'HTTP/1.1\r' +
'\nAccept: application/json, text/plain, */*\r' +
'\nContent-Type: application/json\r' +
'\nUser-Agent: axios/0.27.2\r' +
'\nContent-Length: 79\r' +
'\nHost: graph.facebook.com\r' +
'\nConnection: close\r' +
'\n\r' +
'\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'POST',
path: '/v12.0/number/messages?access_token=Mytoken',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Writable],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object]
},
data: { error: [Object] }
}
}
If I remove the '1' in the 'from' variable I receve it, but whatsapp send it several times with different messages that I don't send every now and then. Is there a way to use the international format?, or a function that I can use to become it?. I think that each country has different formats so, use a function that remove the '1' in 3rd position isn't correct and I don't know if that is caused by the format and the several sends.
What Can I do?. Thanks.