【发布时间】:2015-01-04 14:08:03
【问题描述】:
我正在尝试将我的应用程序与支付网关集成。
他们的 API 基于 REST API 并使用 JSON 来传输数据。他们有这个示例代码
$ curl -X POST -H "Content-Type: application/json" \
-u APIKEYEXAMPLEAPIKEYEXAMPLE:APIKEYEXAMPLEAPIKEYEXAMPLE \
https://api.netbanx.com/hosted/v1/orders \
-d '{
"merchantRefNum" : "ABCDE12345",
"currencyCode" : "USD",
"totalAmount" : 1234
}'
我正在尝试使用它来开发相同的 php 代码。到目前为止我的代码是这样的,我接受了下面提供的答案并进行了一些修改,这是我的代码。
<?php
//API Url
$url = 'https://api.netbanx.com/hosted/v1/orders';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'merchantRefNum' => '89983483',
'currencyCode' => 'USD',
'totalAmount' => '1234'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Set the header authorization
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'Authorization: Basic ZGV2Y2VudHJlNDYxNzpCLXFhMi0wLTU0OGEwM2RkLTMwMmQwMjE1MDA4M2VhZTUwYjQxYzQ0ZDIwMTE4OGM3ZmY4Yjc0ZDIxMzUwY2NiMjdiMDIxNDYwMDc4MGFlMTRkM2E2MTEzY2RmMmJkODc5MjJmZjU3MWQwMGY0ZWU=');
//Execute the request
$result = curl_exec($ch);
?>
我的测试API Key devcentre4617:B-qa2-0-548a03dd-302d02150083eae50b41c44d201188c7ff8b74d21350ccb27b0214600780ae14d3a6113cdf2bd87922ff571d00f4ee
正如他们的文档中所说,我将 API 密钥转换为 base64 添加了单词 Basic 给出了一个空格,并将 HTTP Authorizatoin 代码设为 Basic ZGV2Y2VudHJlNDYxNzpCLXFhMi0wLTU0OGEwM2RkLTMwMmQwMjE1MDA4M2VhZTUwYjQxYzQ0ZDIwMTE4OGM3ZmY4Yjc0ZDIxMzUwY2NiMjdiMDIxNDYwMDc4MGFlMTRkM2E2MTEzY2RmMmJkODc5MjJmZjU3MWQwMGY0ZWU=
在执行时我不断得到
{"error":{"code":401,"message":"Not authorised"}}
我的代码有问题吗?还是其他地方的问题?
更新!!!
这是工作代码,问题在于 API 文档,测试 api 是 https://api.test.netbanx.com/hosted/v1/orders
<?php
//API Url
$url = 'https://api.test.netbanx.com/hosted/v1/orders';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'merchantRefNum' => '89983483',
'currencyCode' => 'USD',
'totalAmount' => '1234'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json and HTTP Authorization code
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("devcentre4617:B-qa2-0-548a03dd-302d02150083eae50b41c44d201188c7ff8b74d21350ccb27b0214600780ae14d3a6113cdf2bd87922ff571d00f4ee") //Base 64 encoding and appending Authorization: Basic
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Execute the request
$result = curl_exec($ch);
?>
【问题讨论】: