Get all the contacts from HubSpot list using API - php

I am using the contact API but it returns maximum 250 contacts only. I used 'vidOffset' parameter for next page but no luck.
Note: I want to export all the contacts from the Hubspot List to my local database using API
Here is my code with php curl:
function callAPI($method, $url, $data){
$curl = curl_init();
$url = $url.'&property=firstname&property=email&count=5&vidOffset=2';
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
// call the function
callAPI('GET', 'https://api.hubapi.com/contacts/v1/lists/11/contacts/all?hapikey=[API key]', false);
Is there anything wrong I am doing? or if there is a better way to get all contact using php/wordpress then please share your experience.

There are a few things to look for here when you make your calls to this API.
Is there a "true" value in the "has-more" field. If so, there are more contacts that can be pulled.
The value of the "vid-offset" field that is returned in your calls.
For the "has-more", this boolean specifies whether or not there are more contacts that you can pull via pagination. For the "vid-offset", this is an integer generated by the API, it does not take a simple sequential integer.
Additionally, you're only grabbing 5 records at a time, you may as well just do the maximum, since it's only 100. This will limit the number of calls you need to make.
Lastly, you may just want to add these to a file, which you can then use for whatever you want, i.e. adding to database, download etc.
So, my suggestion is to amend your initial function to check for the "has-more" value of "true", if it is true send the "vid-offset" value to a new function that makes another call. In that function, you can continue to check for those values, and run your function as many times as it takes until that "has-more" value turns up false.
// the rest of your function is above
// Decode the result so you can traverse the data
$contacts = json_decode($result);
// Store 'has-more' value
$has_more = $contacts->has-more;
// Check if there are more records
if($has_more) {
// Get the offset number provided by API
$offset = $contacts->vid-offset;
// Get more records
getMore($offset);
} else {
// Complete calls and do something else...
}
}
function getMore($offset) {
// Make cURL call with your your offset value
$url = $url.'&property=firstname&property=email&count=100&vidOffset=' . $offset;
$contacts = json_decode($result);
$has_more = $contacts->has-more;
if($has_more) {
$offset = $contacts->vid-offset;
getMore($offset);
} else {
// Complete calls and do something else...
}
}
The documentation that they provide is actually quite clear, so I would read it over a bit as well.

Related

cURL PHP multiple requests for a dynamic URL (Looping Unknown Times)

I'm new to cURL & I'm trying to retrieve data from a dynamic URL. I've successfully retrieved data from 1 page only, but what I want is retrieving data from all pages. The problem here is that pages are variable; I don't know how many time the code should loop to loop over all pages. i.e. the number of pages varies from one case to another, and a good program is the one that works in as many cases as possible. Consequently, putting the links in an array and looping over them isn't the right solution for this.
Here's a quick explanation of the URL I'm trying to retrieve data from:
https://link-search.api.cj.com/v2/link-search?website-id=[Your-ID]&link-type=banner
&advertiser-ids=1513033&records-per-page=100&page-number=' . $num
Did you notice the last variable $num? That should represent the number of the page from where data will be retrieved from. In some cases, it could be only 1, and in some other cases, it could be 10, 12 or 15 (it varies) depending on the parameters I choose, whether I want to see everything or filter some information.
Now here is the problem. How to dynamically increment that number as long as the request returns data? and if not, cURL should stop running?
Here's the code:
<?php
$num = 1;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "XGET");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_ENCODING, "UTF-8");
curl_setopt($curl, CURLOPT_URL, 'https://link-search.api.cj.com/v2/link-search?website-id=[Your-ID]&link-type=banner&advertiser-ids=1513033&records-per-page=100&page-number=' . $num);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_COOKIE,true);
$result = curl_exec($curl);
$xml = simplexml_load_string($result) or die("Error: Cannot create object");
if (curl_errno($curl)) {
echo 'Error:' . curl_error($curl);
}
curl_close($curl);
?>
You can define your curl request inside the function and call that function like this:
<?php
$GLOBALS['num'] = 1;
function curlRequest()
{
// HERE DEFINE YOUR CURL REQUEST
// https://yourUrl.com?$GLOBALS['num']
if (curl_errno($curl)) {
echo 'Error:' . curl_error($curl);
// Exit from function in case there is no output
return;
} else {
$GLOBALS['num']++;
// Call the function to fetch NEXT page
curlRequest();
}
}
// Call the function for first time
curlRequest();
Assuming that curl will fire error if page number not exist or you can implement if condition from the result you are getting. Hope you will get some idea from this.
The main part here is if & else. You should implement if condition on the output you are getting and if page not exist then output will be different so you can simply return from the function in this case.

MailChimp API v3 - Unable to PATCH/ Update?

I am trying to simply add/ remove (well subscribe/ unsubscribe rather than delete) email addresses upon sign up of my website to a MailChimp list using the API. When the user is approved on my site, the email address is added via API successfully if the correct checkbox is ticked. However I can not for the life of me get unsubscribe to work. I think I'm having issues with the PATCH method. The code doesn't error, however the user status in the list does not change to unsubscribed and if I echo out the API call I simply get the following:
{"id":"EMAIL_HASH","email_address":"EMAIL_UNHASHED","unique_email_id":"3dae8dd13a","email_type":"html","status":"subscribed","merge_fields":{"FNAME":"","LNAME":"","MMERGE3":"","MMERGE4":"","MMERGE5":"","MMERGE6":"","MMERGE7":"","MMERGE8":"","MMERGE9":"","MMERGE10":""},"interests":{"edf7fefb79":false},"stats":{"avg_open_rate":0,"avg_click_rate":0},"ip_signup":"","timestamp_signup":"","ip_opt":"77.68.14.17","timestamp_opt":"2018-11-23T14:02:27+00:00","member_rating":2,"last_changed":"2018-11-23T14:02:27+00:00","language":"","vip":false,"email_client":"","location":{"latitude":0,"longitude":0,"gmtoff":0,"dstoff":0,"country_code":"","timezone":""},"tags_count":0,"tags":[],"list_id":"LIST_ID","_links":[{"rel":"self","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Response.json"},{"rel":"parent","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/CollectionResponse.json","schema":"https://us6.api.mailchimp.com/schema/3.0/CollectionLinks/Lists/Members.json"},{"rel":"update","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"PATCH","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Response.json","schema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/PATCH.json"},{"rel":"upsert","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"PUT","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Response.json","schema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/PUT.json"},{"rel":"delete","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH","method":"DELETE"},{"rel":"activity","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/activity","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Activity/Response.json"},{"rel":"goals","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/goals","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Goals/Response.json"},{"rel":"notes","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/notes","method":"GET","targetSchema":"https://us6.api.mailchimp.com/schema/3.0/Definitions/Lists/Members/Notes/CollectionResponse.json"},{"rel":"delete_permanent","href":"https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/EMAIL_HASH/actions/delete-permanent","method":"POST"}]}
which seems more like a dump of possible actions, rather than a response to my call. Needless to say LIST_ID and EMAIL_HASH are accurate and not in the final code.
curl options are as follows, am I possibly missing something require to patch but not POST?
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
curl_setopt($curl, CURLOPT_USERPWD, "user:API_KEY");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
Any help would be appreciated as extensive googling has not returned this problem, predominantly it's people trying to re-add deleted subscribers which this obviously isn't.
$url = 'https://us6.api.mailchimp.com/3.0/lists/LIST_ID/members/'.md5(strtolower($email));
$api_data = array(
'status' => 'unsubscribed'
);
$api_data = json_encode($api_data);
$test_call = CallAPI("PATCH","$url",$api_data);
The PHP using the custom function to call the API. I think I've included the relevant curl info from inside the function but if not please just let me know.
Your function doesn't set any data for a PATCH request. You need to set CURLOPT_POSTFIELDS same as with a POST request:
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
if ($data){
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
Incidentally, the same should be done for a PUT request or any other request type where you need to pass data parameters. You may also want to take a look at my answer here for a function that can both create and update list members.

PHP request data from HTTPS

First of all, I am new in programming. I want to request specific data from another server (data from MSSQL) and transfer (insert) into my MySQL DB, what's the proper way to gain this purpose?
PURPOSE:
A member from MSSQL side would like to transfer certain amount of
points to MySQL, member could input how much of points they had, once
the points is transfer into MySQL successful, a notify script would
send to MSSQL side for update in their end.
What should be generate on MSSQL end, so that MySQL can get these data for further processing?
For example, I have HTTPS link: https://www.example.com/request-transfer.aspx?id=12345&sym=hello&name=linda
For PHP processing end, how can I use cURL to get these data?
I have below script for test, isn't enough to just use $_GET?
// GET
$id = $_GET['id'];
$sym = $_GET['sym'];
$name = $_GET['name'];
$data = array("id" => $id, "sym" => $sym, "name" => $name);
$data_string = json_encode($data);
$ch = curl_init('http://localhost/test/process.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$input = json_decode($data_string);
echo $input->id.', '.$input->sym.', '.$input->name;
echo $result;
Please advise.
You code looks ok so far, just don't set the headers. They will be set automatically on GET/POST requests. Only on PUT requests you need to specify them.
You could JSON stringify the $_GET array directly. This would allow any parameters to be sent to the remote site. If you want to ensure only valid parameters may be sent, you have done it correct. You just should test if the GET parameter is actually present.
If you do not want repeated long expressions, you could write a short function:
function _GET()
{ $n = func_num_args();
for($i = 0 ; $i<$n ;)
{ $key = func_get_arg($i++);
$array[$key] = isset($_GET[$key]) ? $_GET[$key] : '';
}
return $array;
}
$data_string = json_encode(_GET('id', 'sym', 'name'));

Simply posting variables through GET in cURL

so I'm trying to make a small API here. I'll be only sending some information via header (get params) and I'm not using any POST parameters.
Here's the code that I've written.
function sendSMS($message, $number)
{
/*** Connection Params **/
/*** Build the request parameters ***/
$service="sms_api_call_receiver.php";
$number="1212";
$message="asas";
$result = sendPost("https://www.domain.com/smsapp/" . $service . "?message=".urlencode($message)."&number=".$number);
return $result;
}//function
function sendPost($Url)
{
// Initialisation
$ch=curl_init();
// Set parameters
curl_setopt($ch, CURLOPT_URL, $Url);
// Return a variable instead of posting it directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Active the POST method
//curl_setopt($ch, CURLOPT_POST, 1) ;
// Request
//curl_setopt($ch, CURLOPT_POSTFIELDS, $strRequest);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// execute the connexion
$result = curl_exec($ch);
// Close it
//return curl_error($ch);
curl_close($ch);
return $result;
}
On the receiver file, I have this code :-
if(isset($_GET['message']))
{
return true;
}
else
{
return "12212";
}
But when I test, the output I get is :-
string '' (length=0)
What am I doing wrong here?
Troubleshooting
I tried to see if curl_error returned anything. But I could see nothing.
Any suggestions here would be helpful.
Are you sure there is something wrong there? If $_GET['message'] is set (in your test example it is) the script (sms_api_call_receiver.php) returns true and stops the execution.
Because it is HTTP request, and the response is empty, you'll get as result in the sendSMS() function string with 0 length.
to get something as response in sendSMS you need to print in sms_api_call_receiver.php instead of using return

Extra value 1 is appending with curl response

From following two files I am getting output (2000)1 but It should only (2000)
After getting value using curl extra 1 is appending, but why?
balance.php
<?php
$url = "http://localhost/sms/app/user_balance.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 2);
curl_setopt($ch,CURLOPT_POSTFIELDS, "id=2&status=Y");
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
user_balance.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("sms",$conn);
$user_id = $_REQUEST["id"];
$sql = "SELECT * FROM user_sms WHERE user_id='$user_id'";
$rec = mysql_query($sql);
if($row = mysql_fetch_array($rec)) {
$balance = $row["user_sms_balance"];
}
echo "(".$balance.")";
?>
From the PHP manual documentation for curl_setopt():
CURLOPT_RETURNTRANSFER - Set value to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
If you don't set CURLOPT_RETURNTRANSFER option to TRUE , then the return value from curl_exec() will be the boolean value of the operation -- 1 or 0. To avoid it, you can set CURLOPT_RETURNTRANSFER to TRUE, like below:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
I can see that last response to this question was made back in 2017....
I have bashed my head around for past day and I finally got the results that I wanted. I had the same problem as the author of this question.
Maybe my solution will help others and if do help please vote it I would appreciate it.
So in my case I have build the plugin and using shortcode and cURL API get I am feeding API data into the shortcode output.
Anyway I had this working but also printing the Extra value , which is the true value from the CURLOPT_RETURNTRANSFER.
I have solved this by passing ob_start() and ob_get_clean() inside of my shortcode function. This has cleaned and return the response that I wanted without the Extra value 1 appending at the end of my data response.
My shortcode function looks like this
function shortcode_init(){
ob_start();
include PLUGIN_URL . 'templates/shortcode.php';
return ob_get_clean();
}
As you can see I am including the additional php where my cURL API call is defined.
In case someone needs this..here you go.
$ch = curl_init();
$url = YOUR API END POINT URL HERE;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
echo $err;
} else {
// this returns the array from object
// then we can easily iterate thought arrays and echo values that we need,
$decoded = json_decode($response, true);
}

Categories