I'm trying to create a variable and place it in an array. Like this:
$ch = curl_init('https://apps.net-results.com/api/v2/rpc/server.php?Controller=Contact');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, 'user:pass');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode(
array(
'id' => uniqid(),
'method' => 'getMultiple',
'jsonrpc' => '2.0',
'params' => array(
'offset' => 0,
'limit' => 50, // 10, 25, or 50
'order_by' => 'contact_email_address', //'contact_email_address' or 'contact_id'
'order_dir' => 'ASC', //'ASC' or 'DESC'
)
)
)
);
$strResponse = curl_exec($ch);
$strCurlError = curl_error($ch);
if (!empty($strCurlError)) {
//handle curl error
echo "Curl Error<br />$strCurlError<br />";
} else {
//check for bad user/pass
if ($strResponse == "HTTP/1.0 401 Unauthorized: Your username name and/or password are invalid.") {
//handle login error
echo "Error<br />$strResponse<br />";
} else {
//successful call, check for api success or error
$objResponse = json_decode($strResponse);
if (property_exists($objResponse, 'error') && !is_null($objResponse->error)) {
//handle error
$intErrorCode = $objResponse->error->code;
$strMessage = $objResponse->error->message;
$strData = $objResponse->error->data;
echo "Error<br />Code: $intErrorCode<br />Message: $strMessage<br />Data: $strData<br />";
} else {
//handle success
//echo "Success<br />";
$objResult = $objResponse->result;
$intTotalRecords = $objResult->totalRecords;
//echo "Total Records: $intTotalRecords<br />";
$arrContacts = $objResult->results;
//echo $arrContacts[0]->country;
//echo $arrContacts[3]->last_name;
//echo "<pre>";
//print_r($arrContacts);
//echo "<pre/>";
}
}
}
I'm not sure this is possible. I have tried doing different things such as creating a class, and placing the function in the class in the array, but it doesn't work. Can anyone give me the correct syntax of what I should try?
If you pass params via post you should use http_build_query() and you can pass it as CURL post fields.
You should set:
$array = [
'id' => uniqid(),
'method' => 'getContactActivity',
'jsonrpc' => '2.0'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://example.site");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));
curl_exec($ch);
curl_close($ch);
Leave out the call to json_encode(). The value of the CURLOPT_POSTFIELDS option should be either an associative array or a string in URL-encoded format. If you use an array, it will automatically encode it for you.
Related
I'm trying to add an array of players_id to send to push notification to specific mobiles, but I keep getting the error "Incorrect player_id format in include_player_ids (not a valid UUID)"
if ($cons) {
$dado1 = array();
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado1 = array(
$row['funcionarioId']
);
array_push($dado2, $dado1);
}
//echo json_encode($dado2);
} else {
$dado2 = array();
array_push($dado2, $dado1);
$retornoVazio = array("Retorno" => $dado2);
EnviaEmailComErro($sql, sqlsrv_errors(), "Consulta_NFCe - ConsultaDados");
array_push($dado2, array("Success" => "0", "Error" => "1"));
echo json_encode($retornoVazio);
}
function sendMessage($produto, $mesa, $comanda, $garcom, $dado2)
{
$content = array(
"en" => " Garçom $garcom \n o pedido: $produto está pronto!\n mesa: $mesa \n comanda: $comanda",
);
**That where it should add the IDS**
$fields = array(
'app_id' => "***",
'include_player_ids' => array($dado2),
'channel_for_external_user_ids' => 'push',
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic ***'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($produto, $mesa, $comanda, $garcom, $dado2);
$return["allresponses"] = $response;
$return = json_encode($return);
the variable $fields print
{"app_id":"***",
"include_player_ids":[
[
["2610ec53-"],
["045eac07-"],
["8fb19bd9-"]
]
]"
And $response:
{"errors":["Incorrect player_id format in include_player_ids (not a valid UUID): [[\"2610ec53-\"], [\"045eac07-\"], [\"8fb19bd9-\"]]"]}
"The players ID are complete in the code, but I deleted it."
In the if ($cons) { you are pushing all sorts of stuff into arrays, simplify it to
if ($cons) {
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado2[] = $row['funcionarioId'];
}
} else {
And in the function make this change
'include_player_ids' => $dado2,
This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)
I'm having a real headache adding a contact to to dotmailer using nusoap. I'm using the AddContactToAddressBook method,but I can't get it to work. The if statement returns success, but echo "<pre>" . print_r($result, true) . "</pre>"; returns nothingand when I check dotmailer there's no new contact there. I've spent weeks trying to get this to work without any success and am at a loss now as to where the problem is!
<?php
$email='test#apitest.com';
function subscribe($email, &$result)
{
$wsdlPath = "https://apiconnector.com/v2/api.svc?wsdl";
$client=new soapclient( $wsdlPath,'wsdl' );
$client->setCredentials("apiuser-xxxxxxxx#apiconnector.com","xxxxxx");
$error = $client->getError();
$result = $client->call('AddContactToAddressBook',array('addressBookId'=>xxxxxx,'email'=>'test#apitest.com'));
if($client->fault) {
$rv = false;
} else {
// Check for errors
if($error) {
$rv = false;
} else {
$rv = true;
}
}
return $rv;
}
echo "<pre>" . print_r($result, true) . "</pre>";
if(subscribe("test#test.com", $result)) {
echo "success<br />";
print_r($result);
} else {
echo "failed<br />";
}
?>
I put the custom fields in another array and that now works. This is what I've now got:
<?php
/** POST EMAIL FIRST AND GET CONTACT FROM DOTMAILER */
$postContactUrl = 'https://apiconnector.com/v2/contacts/';
$data = array(
'Email' => 'test#apitest.com', //email to post
'EmailType' => 'Html', //other option is PlainText
'dataFields' => array(
array(
'Key' => 'CITY',
'Value' => $_POST['address2']),
array(
'Key' => 'COUNTRY',
'Value' => $country_name),
array(
'Key' => 'FIRSTNAME',
'Value' => $_POST['name_first']),
array(
'Key' => 'FULLNAME',
'Value' => $_POST['name_first']." ".$_POST['name_last'] ),
array(
'Key' => 'LASTNAME',
'Value' => $_POST['name_last']),
array(
'Key' => 'POSTCODE',
'Value' => $_POST['postcode']),
array(
'Key' => 'STREET',
'Value' => $_POST['address1']),
array(
'Key' => 'TOWN',
'Value' => $_POST['address3']),
)
);
//post email and response will be contact object from dotmailer
$contact = execute_post($postContactUrl, $data);
/** ADD CONTACT TO ADDRESS BOOK */
$addContactToAddressBookUrl = 'https://apiconnector.com/v2/address-books/' . 'address-book-id' . '/contacts'; //add your address book id
//post contact to address book and response will be address book object from dotmailer
$book = execute_post($addContactToAddressBookUrl, $contact);
/**
* if you want to check if there was an error you can
* check it by calling this on response.
* example $book->message
*/
echo "<pre>" . print_r($data, true) . "</pre>";
// echo "<pre>" . print_r($contact, true) . "</pre>";
// echo "<pre>" . print_r($book, true) . "</pre>";
//Function to initiate curl, set curl options, execute and return the response
function execute_post($url, $data){
//encode the data as json string
$requestBody = json_encode($data);
//initialise curl session
$ch = curl_init();
//curl options
curl_setopt($ch, CURLAUTH_BASIC, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, 'user-name' . ':' . 'password'); // credentials
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: ' . 'application/json' ,'Content-Type: application/json'));
//curl execute and json decode the response
$responseBody = json_decode(curl_exec($ch));
//close curl session
curl_close($ch);
return $responseBody;
}
?>
You made a couple of mistakes in your script. Class name is SoapClient not soapclient. You will also need to use curl to accomplish what you want to do.
I work for dotmailer so i can explain you a bit first. You cannot post/add an email to address book directly. You need to post the email to dotmailer first, you will get contact object in response. Than you can use that contact object to post/add you email/contact to address book.
Below you will find complete fully working example of what you will need to do. Also follow this link to read api description https://apiconnector.com/v2/help/wadl
<?php
/** POST EMAIL FIRST AND GET CONTACT FROM DOTMAILER */
$postContactUrl = 'https://apiconnector.com/v2/contacts/';
$data = array(
'Email' => 'test#apitest.com', //email to post
'EmailType' => 'Html', //other option is PlainText
);
//post email and response will be contact object from dotmailer
$contact = execute_post($postContactUrl, $data);
/** ADD CONTACT TO ADDRESS BOOK */
$addContactToAddressBookUrl = 'https://apiconnector.com/v2/address-books/' . 'address-book-id' . '/contacts'; //add your address book id
//post contact to address book and response will be address book object from dotmailer
$book = execute_post($addContactToAddressBookUrl, $contact);
/**
* if you want to check if there was an error you can
* check it by calling this on response.
* example $book->message
*/
echo "<pre>" . print_r($contact, true) . "</pre>";
echo "<pre>" . print_r($book, true) . "</pre>";
//Function to initiate curl, set curl options, execute and return the response
function execute_post($url, $data){
//encode the data as json string
$requestBody = json_encode($data);
//initialise curl session
$ch = curl_init();
//curl options
curl_setopt($ch, CURLAUTH_BASIC, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, 'user-name' . ':' . 'password'); // credentials
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Accept: ' . 'application/json' ,'Content-Type: application/json'));
//curl execute and json decode the response
$responseBody = json_decode(curl_exec($ch));
//close curl session
curl_close($ch);
return $responseBody;
}
I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';
I have a custom function that uses cURL to make a request and then handle the response. I use it in a loop and the function itself works fine. But, when used inside of a loop, the function that is supposed to be executed first often doesn't. Seems like the sequence in which the posts are supposed to occur are totally neglected.
function InitializeCurl($url, $post, $post_data, $token, $form, $request) {
if($post) {
if($form) {
$default = array('Content-Type: multipart/form-data;');
} else {
$default = array('Content-Type: application/x-www-form-urlencoded; charset=utf-8');
}
} else {
$default = array('Content-Type: application/json; charset=utf-8');
}
// Add the authorization in the header if needed
if($token) {
$push = 'Authorization: Bearer '.$token;
array_push($default, $push);
}
$headers = array_merge($GLOBALS['basics'], $default);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.test.com/'.$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
if($request) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($post) {
if($form === false) {
$post_data = http_build_query($post_data);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);
return $response;
}
// Define the token
$token = "sample_token";
$msg = array('msg_1', 'msg_2', 'msg_3', 'msg_4', 'msg_5', 'msg_6', 'msg_7', 'msg_8', 'msg_9', 'msg_10');
for($i=0;$i<count($msg);$i++) {
$post_data = array("content_type" => "text",
"body" => $msg[$i]);
$info = InitializeCurl("send_message/", true, $post_data, $token, false, false);
$decode = #json_decode($info, true);
}
The loop should make it so that each message is posted after one another in order. But, it's totally not. Would adding CURLOPT_TIMEOUT fix this?
Seems you are missing some code, but anyway, you would probably be better off using this CURL class, or rather classes:
http://semlabs.co.uk/journal/multi-threaded-stack-class-for-php
See examples. You will be returned a result with all the URLs. You can loop through to get details of the URL etc. like this:
$urls = array(
1 => 'http://seobook.com/',
2 => 'http://semlabs.co.uk/',
64 => 'http://yahoo.com/',
3 => 'http://usereffect.com/',
4 => 'http://seobythesea.com/',
5 => 'http://darkseoprogramming.com/',
6 => 'http://visitwales.co.uk/',
77 => 'http://saints-alive.co.uk/',
7 => 'http://iluvsa.blogspot.com/',
8 => 'http://sitelogic.co.uk/',
9 => 'http://tidybag.co.uk/',
10 => 'http://felaproject.net/',
99 => 'http://billhicks.com/'
);
$opts = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
);
$hs = new CURLRequest();
$res = $hs->getThreaded( $urls, $opts, 5 );
foreach( $res as $r )
{
print_r( $r['info'] ); # prints out verbose info and data of URL etc.
print_r( $r['content'] ); # prints out the HTML response
}
But the result will be returned in sequence, so you can also identify the response by index.