You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET调用PayPal OAuth API获取access token返回401 Unauthorized错误

问题原因
  • 核心错误:Basic认证格式不符合规范
    OAuth2 Client Credentials模式要求Basic认证头的内容为Basic [Base64编码后的<client_id>:<client_secret>字符串],你当前代码直接将明文的client id和secret拼接在Basic 后,没有做Base64编码,是触发401错误的主要原因。
  • 次要错误:冗余请求头干扰
    你额外添加了Username和Password两个自定义请求头,PayPal的v1/oauth2/token接口不需要这两个头,多余的头信息可能触发接口安全校验拦截。
修正后的代码
Dim uri as new Uri("https://api-m.sandbox.paypal.com/v1/oauth2/token")
Dim wClientID As String = "你的沙箱client ID"
Dim wClientSecret As String = "你的沙箱Client Secret"
Dim data as string = "grant_type=client_credentials"
Dim dataByte as Byte()
Dim request As HttpWebRequest

ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

request = WebRequest.Create(uri)
' 生成符合规范的Basic认证头
Dim authRaw As String = wClientID & ":" & wClientSecret
Dim authBytes As Byte() = Encoding.UTF8.GetBytes(authRaw)
Dim authBase64 As String = Convert.ToBase64String(authBytes)
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " & authBase64)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"

dataByte = Encoding.UTF8.GetBytes(data)

Using requestStream = request.GetRequestStream()
    requestStream.Write(dataByte, 0, dataByte.Length)
End Using

' 后续可添加获取响应的逻辑
' Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
'     处理响应内容
' End Using
额外校验点

如果修改后仍有问题,请检查以下配置:

  • 确认使用的client id和secret对应沙箱环境,不要和生产环境的凭证混用
  • 确认你使用的.NET版本支持TLS1.2,.NET Framework 4.5及以上版本默认支持TLS1.2

内容的提问来源于stack exchange,提问作者BTinfinity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:45:03