使用Mozilla Backpack Connect API和PHP

时间:2015-05-29 14:19:23

标签: php json curl openbadge

我想使用 Mozilla Backpack Connect API check this !)发行徽章。为此,我已经关注this document,但我仍然无法发出徽章!

当我尝试使用刷新令牌获取新的访问令牌时,我遇到了完全相同的问题。所以我发布了#34;获取新的访问令牌"这里的代码因为它比发行代码更容易理解。

我想在 PHP 中使用 cURL 执行此操作,而不是在 Javascript 中执行此操作。

这是我的代码:

$data = array(
    'grant_type' => 'refresh_token',
    'refresh_token' => $refreshToken
);
$url = $apiRoot .'/token';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, fopen('php://output', 'w+'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
var_dump($response);

curl_close($ch);

在这里,我只是尝试获取一个新的访问令牌,如the same document中所述,但不幸的是,我总是得到这样的回复:

  

错误请求:错误请求
  在下一个(/var/www/openbadges/node_modules/express/node_modules/connect/lib/proto.js:125:13)
  at /var/www/openbadges/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:54:23
  在IncomingMessage。 (/var/www/openbadges/node_modules/express/node_modules/connect/lib/middleware/json.js:74:60)
  在IncomingMessage.emit(events.js:92:17)
  at _stream_readable.js:938:16
  at process._tickCallback(node.js:419:13)

如果我看得更深,我已经对这个请求进行了诽谤,它给了我这个:

  

> POST / api / token HTTP / 1.1
  主持人:backpack.openbadges.org
  接受: /
  内容类型:application / json
  内容长度:81

     

*上传已完全发送:81个字节中的81个
  *额外的东西不精细transfer.c:1037:0 0
  * HTTP 1.1或更高版本,具有持久连接,支持流水线技术   < HTTP / 1.1 400错误请求
  <缓存控制:no-cache =" set-cookie"
  <内容类型:text / plain
  <日期:2015年5月29日星期五12:36:03 GMT
  < Set-Cookie:AWSELB = 674101290634B07D75A3C1417FA6788D6E65270EC8D2D0E6014FB81FA4E878CAEA117D6E6334DB190F94A3D84909E9928F08D6B81651BDC3386AFC0A84F3A39F4B51E09B31; PATH = /; MAX-AGE = 3600
  < x-frame-options:DENY
  < X-Powered-By:Express
  <内容长度:478
  <连接:保持活力
  <
  *连接#0到主机backpack.openbadges.org保持完好   *关闭连接#0

所以,基本上,它会给我一个错误400" Bad Request"没有更多信息...

有关信息,如果我尝试使用 Javascript 进行操作,则可以。如果我这样做:

$.ajax({
    type: 'POST',
    url: 'https://backpack.openbadges.org/api/token',
    data: {
        grant_type: 'refresh_token',
        refresh_token: theRefreshToken
    },
    headers: {
        'Content-Type': 'application/json'
    },
    success: function(data, textStatus, req) {
        console.log(textStatus);
        console.log(data);
    },
    error: function(xhr, textStatus, err) {
        console.log(textStatus);
        console.log(err);
        console.log(xhr);
        console.log($(this));
    }
});

这让我很成功,但是当我使用 PHP cURL 时,它不起作用!那为什么呢?

我的徽章有效(它会毫无问题地通过the validation。)

1 个答案:

答案 0 :(得分:0)

我搜索了好几个小时!解决方案非常简单但不那么明显......

在这一行:curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));您必须使用json_encode()而不是http_build_query()

这样做:curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));并且它有效!耶!