使用GF WebAPI从外部站点创建新的Gravity Forms条目

时间:2014-09-19 02:50:27

标签: wordpress rest curl gravity-forms-plugin

我有2个网站。

  • Sita A运行Wordpress并具有Gravity Forms。
  • 网站B正在尝试使用Gravity Forms Web API向网站A中的重力表格添加条目

无论我尝试什么,我能得到的最好结果是创造了一个"资源"带有空响应对象的响应(201)。无论成功响应如何,都不会创建记录。

{"status":201,"response":[]}

我可以成功获取数据,因此我不认为这是一个身份验证问题。文档说明响应应包含"描述结果的本地化消息:"条目已成功创建""。

我已尝试指向 / entries 以及 / forms / $ form_id / entries

我安装了Web API客户端插件并成功创建了一个记录。我也把这些代码倾倒了一千次。该插件uses wp_remote_request发布我无法使用的数据,因为我没有运行Wordpress。

这是当前的代码:

<?php
$api_key = '123';
$private_key = 'abc';
$method  = 'POST';
$endpoint = 'http://example.com/gravityformsapi/';
$route = 'entries';
//$route = 'forms/17/entries';
$expires = strtotime('+60 mins');
$string_to_sign = sprintf('%s:%s:%s:%s', $api_key, $method, $route, $expires);
$sig = calculate_signature($string_to_sign, $private_key);

$api_call = $endpoint.$route.'?api_key='.$api_key.'&signature='.$sig.'&expires='.$expires;

$data = array(
    "id" => "",
    "date_created" => "",
    "form_id" => "17",
    "1" => "test3@test.com"
);

$ch = curl_init($api_call);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);

print_r($result);

1 个答案:

答案 0 :(得分:1)

你的代码很接近。我使用json_encode代替http_build_query

您可能需要查看潜在客户表中的某些孤立条目。

以下是一些对我有用的代码:

<?php
$api_key = 'keyhere';
$private_key = 'privatekey';
$method  = 'POST';
$endpoint = 'https://www.site.com/gravityformsapi/';
//$route = 'entries';
$route = 'forms/1/entries';
$expires = strtotime('+60 mins');
$string_to_sign = sprintf('%s:%s:%s:%s', $api_key, $method, $route, $expires);
$sig = calculate_signature($string_to_sign, $private_key);

$api_call = $endpoint.$route.'?api_key='.$api_key.'&signature='.$sig.'&expires='.$expires;

//array of entries (each entry is an array with key=field id)
$entries = array(
    array("status"=>"active","1.3"=>"firstname","1.6"=>"lastname","2"=>"","3"=>"test@test.com","4"=>"testtest","5"=>"something else")
);

$ch = curl_init($api_call);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($entries));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);

print_r($result);//201 status indicates it inserted the entry. Should return id of the entry.

function calculate_signature($string, $private_key) {
    $hash = hash_hmac("sha1", $string, $private_key, true);
    $sig = rawurlencode(base64_encode($hash));
    return $sig;
}
?>