如何在VBA中获取REST API令牌并存储至变量?
问题排查及解决方法
1. 官方API令牌获取规则(基于提供的API文档翻译)
官方OAuth2令牌端点为https://api.valenciaportpcs.net/messaging/oauth/token,使用Client Credentials授权模式时需满足:
- 请求方法:POST
- 内容类型:
application/x-www-form-urlencoded(而非JSON格式) - 必填参数:
grant_type=client_credentials、client_id、client_secret - 也可通过Basic Auth方式传递凭证:将
client_id:client_secret做Base64编码后放入Authorization请求头
2. VBA代码问题修正
你的代码存在3处关键错误:
- 使用了错误的API端点地址
- 请求格式不符合服务器要求(JSON不被接受)
- 弹窗调用了未定义的
responseText变量,实际变量为response
修正后的完整代码:
Sub LOGIN() Dim Request As Object Dim stUrl As String Dim response As String Dim requestBody As String ' 替换为官方正确的令牌端点 stUrl = "https://api.valenciaportpcs.net/messaging/oauth/token" Set Request = CreateObject("MSXML2.XMLHTTP") ' 采用表单格式传递参数,替换为你的真实凭证 requestBody = "grant_type=client_credentials&client_id=你的用户名&client_secret=你的密码" With Request .Open "POST", stUrl, False .setRequestHeader "Content-type", "application/x-www-form-urlencoded" .send requestBody response = .responseText ' 检查请求状态,便于排查问题 If .Status <> 200 Then MsgBox "请求失败:状态码 " & .Status & vbCrLf & .statusText Else MsgBox response ' 将响应存储到Sheet1的A1单元格 ThisWorkbook.Sheets("Sheet1").Range("A1").Value = response End If End With Set Request = Nothing End Sub
3. Curl命令修正
原命令参数混乱,修正后两种可用方式:
方式1:直接传递表单参数
curl -X POST "https://api.valenciaportpcs.net/messaging/oauth/token" -d "grant_type=client_credentials" -d "client_id=你的用户名" -d "client_secret=你的密码"
方式2:使用Basic Auth授权
curl -X POST "https://api.valenciaportpcs.net/messaging/oauth/token" -u "你的用户名:你的密码" -d "grant_type=client_credentials"
额外提示
- 务必将代码和命令中的占位符替换为真实有效凭证
- 若仍无响应,检查网络是否可访问该API(比如是否需要代理)
- VBA中的
Status和statusText可帮助判断服务器返回的错误信息
内容的提问来源于stack exchange,提问作者Antonio Moyano
相关产品推荐
相关产品推荐

