只是为了好玩,也许是为了将来的使用,我尝试运行一个 VBA 代码,每当有事情发生时它都会发送一条 WhatsApp 消息。
现在我在转换 WhatsApp 提供的 API CURL 命令时遇到问题:
curl -X POST \
'https://graph.facebook.com/v18.0/FROM_PHONE_NUMBER_ID/messages' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-H 'Content-Type: application/json' \
-d '
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "PHONE_NUMBER",
"type": "text",
"text": { // the text object
"preview_url": false,
"body": "MESSAGE_CONTENT"
}
}'
使用一些有关如何发送短信的代码示例,我得到了这一点:
Private Sub CommandButton4_Click()
Dim INSTANCE_ID, URL As String
Dim REQUEST As Object
INSTANCE_ID = "EAA..."
URL = "https://graph.facebook.com/v17.0/196.../messages"
Set REQUEST = CreateObject("MSXML2.ServerXMLHTTP.6.0")
With REQUEST
.Open "POST", URL
.setRequestHeader "Authorization", "Bearer " & INSTANCE_ID
.setRequestHeader "Content-Type", "application/json"
.send "messaging_product=whatsapp&recipient_type=individual&to=5511...&type=text&text:{body:TEST}"
End With
Application.Wait Now() + TimeSerial(0, 0, 1)
Debug.Print "Status: " & REQUEST.Status & " - Text: " & REQUEST.responseText
Set REQUEST = Nothing
End Sub
执行上面的代码,响应为:
Status: 400 - Text: {"error":{"message":"(#100) Invalid parameter","type":"OAuthException","code":100,"error_data":{"messaging_product":"whatsapp","details":"Parameter 'text' is mandatory for type 'text'"},"fbtrace_id":"AWr..."}}
这是我第一次尝试通过 VBA 执行 API。 我知道在 Java 上运行这个会容易得多,但我认为这个挑战会提高我对这个主题的理解。
提前致谢!
尤里卡!
意识到错误是由我制作的糟糕的 JSON 引起的(感谢 S Meaden),我在 StackOverflow 上找到了一篇非常好的帖子,展示了如何创建正确的 JSON。
解决方案:对象转JSON
工作代码:
Private Sub CommandButton4_Click()
Dim INSTANCE_ID, URL As String
Dim REQUEST As Object
Dim body As String
Set dictSubValues = CreateObject("Scripting.Dictionary")
Set dictBody = CreateObject("Scripting.Dictionary")
INSTANCE_ID = "EAA..."
URL = "https://graph.facebook.com/v17.0/196.../messages"
Set REQUEST = CreateObject("MSXML2.ServerXMLHTTP.6.0")
dictSubValues.Add "preview_url", "false"
dictSubValues.Add "body", "TEST"
dictBody.Add "messaging_product", "whatsapp"
dictBody.Add "recipient_type", "individual"
dictBody.Add "to", "5511..."
dictBody.Add "type", "text"
dictBody.Add "text", dictSubValues
body = ToJson(dictBody)
With REQUEST
.Open "POST", URL, False
.setRequestHeader "Authorization", "Bearer " & INSTANCE_ID
.setRequestHeader "Content-Type", "application/json"
.send body
End With
Application.Wait Now() + TimeSerial(0, 0, 1)
Debug.Print "Status: " & REQUEST.Status & " - Text: " & REQUEST.responseText
Set REQUEST = Nothing
End Sub
回复:
状态:200 - 文本:{"messaging_product":"whatsapp","contacts":[{"input":"5511977406137","wa_id":"5511977406137"}],"messages":[{"id": “wamid.HBgNNTUxMTk3NzQwNjEzNxUCABEYEjlCNzY3NTI5QjdCQkYzQzk5NAA=”}]}