You need to enable JavaScript to run this app. PayPal沙箱转生产环境交易搜索API无数据返回问题
优惠活动
大模型
产品
解决方案
定价
更多

PayPal沙箱转生产环境交易搜索API无数据返回问题

问题概述

本次遇到的为PayPal通用API类问题,基于PayPal交易搜索API开发的R语言数据拉取程序,在沙箱环境运行正常,切换生产环境后无法正常返回交易数据。

  • 程序核心功能:拉取PayPal账户交易数据并整理为dataframe结构展示
  • 沙箱环境运行表现:使用沙箱凭证可正常加载沙箱环境留存的1笔交易,全流程无报错
  • 生产环境运行表现:切换生产凭证后,对应关联的真实PayPal账户内交易数量远多于沙箱环境,但接口无任何有效交易数据返回
上线切换操作记录

切换生产环境时仅做了两处修改,无其他额外调整:

  • 将接口请求地址从沙箱地址替换为生产地址https://api.paypal.com
  • 将沙箱的用户名、密码替换为生产环境对应的凭证信息
已完成的自查项
  • 登录生产应用的设置界面,已勾选交易搜索API对应的权限选项,确认权限为当前生产应用开通
  • 默认开发者账户、生产应用已与公示关联的PayPal账户邮箱绑定,具备拉取该真实账户下交易数据的权限
附R语言实现代码
library(curl)
library(lubridate)
library(rjson)
library(magrittr)
library(dplyr)

# 代码基于curl库功能、PayPal交易搜索API实现

sandbox.creds <- list(username = "sandbox_username",
                password = "sandbox_password")

live.creds <- list(username = "live_username",
                      password = "live_password")

# 全局变量初始化
api_url <- " "
user_pwd <- " "

access.token <<- NA
access.token.expires <<- NA

# 环境切换函数
live.or.sandbox <- function(live) {
  # 每次调用时重置访问令牌,避免不同环境的令牌缓存导致鉴权错误
  access.token <<- NA
  access.token.expires <<- NA
  
  if (live == TRUE) {
    print("切换为生产环境凭证")
    api_url <<- "https://api.paypal.com"
    user_pwd <<- paste0(live.creds[[1]],":",live.creds[[2]])
  }
  else {
    print("切换为沙箱环境凭证")
    api_url <<- "https://api.sandbox.paypal.com"
    user_pwd <<- paste0(sandbox.creds[[1]],":",sandbox.creds[[2]])
  }
}

# 默认设置为生产环境
live.or.sandbox(live = TRUE)

# 访问令牌获取逻辑
get.access.token <- function() {
      req_access_token <- curl::new_handle() %>%
        handle_setopt(copypostfields = "grant_type=client_credentials", userpwd = user_pwd, verbose=TRUE, httpauth = 1L) %>%
        handle_setheaders("Accept" = "application/json", 
                          "Accept-Language" = "en_US") %>%
        curl_fetch_memory(url = paste0(api_url, "/v1/oauth2/token")) %$% content %>% 
        rawToChar %>% rjson::fromJSON()
      
      access.token.expires <<- lubridate::as_datetime(lubridate::as_datetime(Sys.time()) + lubridate::dseconds(req_access_token$expires_in))
      access.token <<- req_access_token$access_token
}

# 令牌有效性校验逻辑
get.access.token.if.current.not.expired <- function() {
  current_time <- lubridate::as_datetime(Sys.time()) 
  
  cat("当前访问令牌状态:", access.token)
  # 无有效令牌时才发起新的令牌请求
  if (is.na(access.token)) {
    print("无有效访问令牌")
    get.access.token()
  }
  else {
    print("已存在访问令牌")
    
    if(access.token.expires < as_date(Sys.time())) {
      print("历史令牌已过期")
      print("获取新令牌")
      get.access.token()
    }
    else {
      print("使用历史有效令牌")
      cat("剩余有效时长(秒):", 
          as.integer(difftime(access.token.expires,
                   as_datetime(Sys.time()),
                   units = "secs")))
    }
  }
}

# 交易数据请求逻辑
make.transaction.request <- function(start_date, end_date) {
  # 令牌有效性校验
  get.access.token.if.current.not.expired()
  
  bearer.access.token <- paste0("Bearer ", access.token)
  req_transactions <- new_handle() %>%
    handle_setheaders("Accept" = "application/json", 
                      "Authorization" = bearer.access.token) %>%
    curl_fetch_memory(url = paste0(api_url,"/v1/reporting/transactions?fields=all&start_date=",start_date,"&end_date=", end_date, "&fields=all")) %$% content %>% 
    rawToChar %>% rjson::fromJSON()
  
  print("发起交易查询请求")
  print(req_transactions)
  
  # 仅返回交易明细字段
  req_transactions$transaction_details
}

# 日期格式化函数(适配PayPal要求的RFC3339格式)
format.date.rfc339 <- function(date) {
  format(lubridate::as_datetime(date), "%Y-%m-%dT%H:%M:%SZ")
} 

# 批量拉取交易逻辑
return.transactions <- function(number_months, tidy_transactions, live) {
  if(live == TRUE) {
    live.or.sandbox(live = TRUE)
  }
  else {
    live.or.sandbox(live = FALSE)
  }
  
  # 单月按30天计算,单次查询最长支持30天范围,需分段拉取更长时间范围的数据
  current_date <- lubridate::as_datetime(Sys.time())
  # 批量生成适配格式的时间区间节点
  dates <- lapply(1:number_months, function(x) format.date.rfc339(current_date - ddays((x*30))) )
  
  res <- list()
  # 逐段发起查询
  for (i in 1:number_months) {
    if (i < number_months) {
      start_date <- dates[[i+1]]
      end_date <- dates[[i]]
      res[[i]] <- make.transaction.request(start_date, end_date)
    }
  }
  
  # 数据整理为表格结构
  if (tidy_transactions == TRUE) {
    transactions <- bind_cols(res)
    names(transactions) <- c("transaction_id", "transaction_event_code",
                              "date", "transaction_updated_date",
                              "currency_code", "value", "transaction_status",
                              "transaction_subject", "currency_code", "value",
                              "currency_code", "value2", "protection_eligibility")
  
    transactions <- transactions[, c("transaction_id", "date", "value")]
    transactions <- transactions %>% mutate(value = sapply(value, function(x) paste0("£", x)),
                                             date = sapply(date, function(x) format(as_date(x), format="%B %d %Y"))
    )
  }
  else {
    res
  }
}

# 分别拉取生产、沙箱环境近4个月的数据
transactions_live <- return.transactions(4, tidy_transactions = FALSE, live = TRUE)
transactions_sandbox <- return.transactions(4, tidy_transactions = FALSE, live = FALSE)
接口调用返回日志

生产环境令牌请求日志

* Connection 90 seems to be dead!
* Closing connection 90
*   Trying 66.211.168.123...
* TCP_NODELAY set
* Connected to api.paypal.com (66.211.168.123) port 443 (#91)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use http/1.1
* Server certificate:
*  subject: C=US; ST=California; L=San Jose; O=PayPal, Inc.; OU=PayPal Production; CN=api.paypal.com
*  start date: Jul 28 00:00:00 2020 GMT
*  expire date: Aug  2 12:00:00 2022 GMT
*  subjectAltName: host "api.paypal.com" matched cert's "api.paypal.com"
*  issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert SHA2 High Assurance Server CA
*  SSL certificate verify ok.
* Server auth using Basic with user 'my_username'
> POST /v1/oauth2/token HTTP/1.1
Host: api.paypal.com
Authorization: Basic blahblahQVZtUWtXlcasdklsdS3VTME93sadjksdjpYlRSXzE2Si11LTVBS19DYnFVX1BlWlBQREcwT25OeTVSTHdQOTVyV0F4WUasdjasdoOUM4bzluQmN6MGg5ckFzbWQ=
User-Agent: RStudio Desktop (1.2.5033); R (3.6.3 x86_64-apple-darwin15.6.0 x86_64 darwin15.6.0)
Accept-Encoding: deflate, gzip
Accept: application/json
Accept-Language: en_US
Content-Length: 29
Content-Type: application/x-www-form-urlencoded

* upload completely sent off: 29 out of 29 bytes
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 972
< Connection: keep-alive
< Date: Mon, 26 Oct 2020 13:05:54 GMT
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Paypal-Debug-Id: 431a3fb2c4f43
< X-Paypal-Token-Service: IAAS
< Strict-Transport-Security: max-age=31536000; includeSubDomains
< 
* Connection #91 to host api.paypal.com left intact

沙箱环境令牌请求日志(对比参考)

生产环境的令牌请求除响应头多了Strict-Transport-Security字段外,其余响应内容、返回状态与沙箱环境完全一致,沙箱日志如下:

* Connection 91 seems to be dead!
* Closing connection 91
* Connection 92 seems to be dead!
* Closing connection 92
*   Trying 173.0.82.78...
* TCP_NODELAY set
* Connected to api.sandbox.paypal.com (173.0.82.78) port 443 (#93)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: C=US; ST=California; L=San Jose; O=PayPal, Inc.; OU=PayPal Production; CN=api.sandbox.paypal.com
*  start date: Jul 27 00:00:00 2020 GMT
*  expire date: Aug  1 12:00:00 2022 GMT
*  subjectAltName: host "api.sandbox.paypal.com" matched cert's "api.sandbox.paypal.com"
*  issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert SHA2 High Assurance Server CA
*  SSL certificate verify ok.
* Server auth using Basic with user 'sandbox_username'
> POST /v1/oauth2/token HTTP/1.1
Host: api.sandbox.paypal.com
Authorization: Basic blahblahT1I3MmJrSk5asjdkasjdkasjdksajkdjaskjdksajdkjsakdadkpasdUDF6cDBscjlnTWxaMXBScnl2WmR2YU91cGM=
User-Agent: RStudio Desktop (1.2.5033); R (3.6.3 x86_64-apple-darwin15.6.0 x86_64 darwin15.6.0)
Accept-Encoding: deflate, gzip
Accept: application/json
Accept-Language: en_US
Content-Length: 29
Content-Type: application/x-www-form-urlencoded

* upload completely sent off: 29 out of 29 bytes
< HTTP/1.1 200 OK
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Content-Length: 972
< Date: Mon, 26 Oct 2020 15:07:46 GMT
< Paypal-Debug-Id: 89a06d70502df
< X-Paypal-Token-Service: IAAS
< 
* Connection #93 to host api.sandbox.paypal.com left intact

生产环境交易查询接口调用日志

从日志可见,交易查询接口返回状态为200,但响应体长度仅442字节,未包含任何交易明细内容

* Found bundle for host api.paypal.com: 0x7f835d4f5810 [can pipeline]
* Could pipeline, but not asked to!
* Re-using existing connection! (#3) with host api.paypal.com
* Connected to api.paypal.com (66.211.168.123) port 443 (#3)
> GET /v1/reporting/transactions?fields=all&start_date=2020-06-28T19:49:23Z&end_date=2020-07-28T19:49:23Z&fields=all HTTP/1.1
Host: api.paypal.com
User-Agent: RStudio Desktop (1.2.5033); R (3.6.3 x86_64-apple-darwin15.6.0 x86_64 darwin15.6.0)
Accept-Encoding: deflate, gzip
Accept: application/json
Authorization: Bearer blahsduas9fuyiwjwf_vX1d_p8n3keJy8ZSvyjZasdkfdkdsfdsLL8MgQf3RN0R9sEHAXystT7EXqlgasdjasdasosCsxjtBotQ

< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 442
< Connection: keep-alive
< Date: Mon, 26 Oct 2020 19:49:25 GMT
< Application_id: APP-09E52asjdasd0071E
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Caller_acct_num: YXGDSFU9DSFBU7TUE
< Paypal-Debug-Id: aadd1bcasduasd239
< Strict-Transport-Security: max-age=31536000; includeSubDomains
< 
* Connection #3 to host api.paypal.com left intact

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 04:36:07