database rows polling service - php

I intend to develop lots of client voting systems capturing the following:
<?php
$data = array(
'vancancy' => 'PE',
'pollingStation' => 'PS1001',
'validVotes' => '400',
'rejectedVotes' => '10',
'validVotes' => '400',
'base64Image' => 'VVVGGFTFTFHNBFVUWWSETD',
'candidate 1' => '200',
'candidate 2' => '100',
'candidate 3' => '190',
'base64Image' => 'VVVGGFTFTFHNBFVUWWSETD');
$payload = json_encode($data);
$url = 'http://localhost/APIS/RMS/jsonapi.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-
Type:application/json'));
$response = curl_exec($ch);
echo $response;
curl_close($ch);
?>
At the central server where the posting is done; i have STAGING database table that receives the json data and keeps it as TEXT.
I want a SERVICE that should regularly poll the STAGING table and split the json TEXT into separate fields to populate in another resulting table (storing candidate 1, 2, 3 and the amount of votes. After each row is read, then a flag in staging table must be set so I read it again. At the results table I must calculate how many votes each candidate has in another total votes.
########### THis is the API code receiving results from clients########
<?php
header("Content-Type:application/json");
require 'checkSQLInsertion.php';
// read the incoming POST body (the JSON)
$input = file_get_contents('php://input');
if($input)
{
$SQLInsertStatus=get_insertStatus($input);
if($SQLInsertStatus)
{
response(200,1);//No SQL Insertion
}
else
{
response(200,0); //Successful SQL Insetion
}
}
else
{
response(400,"If you can see this, then Web Service is Working, try
again!! ");
}
function response($status,$ack)
{
header("HTTP/1.1 ".$status);
$response['status']=$status;
$response['status_message']=$ack;
$json_response = json_encode($response);
echo $json_response;
}

Related

PHP API request by GET details

I'm trying to get the details from this example (i created the code right now).
But i'm very... confused... how can i get the details of the link, then separate and send to my MYSQL database..
<?php
$ch = curl_init();
$url = "https://reqres.in/api/users?page=2";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
if($e = curl_error($ch)) {
echo $e;
}
else {
$decoded = json_decode($resp, true);
//print_r($decoded);
foreach($decoded as $key => $item) {
$array = array(
'id' => ,
'email' => ,
'first_name' => ,
'last_name' => ,
);
print_r($array);
}
}
curl_close($ch);
?>
If you call the url in your browser then you will see that the result array is present in the data field.
You may check this by printing the whole result:
print_r($decoded);
So if you like to print_r the results it should be simply
print_r($decoded['data']);
If you like to store it in your database you may walk through the array and store each item
foreach($decoded['data'] as $item) {
storeItem($item);
}
To make this work you should implement the storeItem function which accepts the array $item and stores it into your database. There are various tutorials about doing that.

Instagram API - How to check last page last record?

I am working on Instagram API first time and also using social media API first time so I have very basic knowledge of how to call and read data from API. So I have created one recursive function to call next page and read data. Now I am storing Media ID, Comments Counts, Likes Counts for each and every post data with next page in my instagram database table. Now I want to insert one another record to my schedule table when API reached to last page and inserted all records to instagram table. I am adding my code below and I will happy if someone guide me to make code more proper :)
My Code Work:
public function User($next=null){
global $TotalHashTagPosts; // Total hashtag post counts
global $CommentsSum; // Sum of comments
global $LikesSum; // Sum of likes
$AccessToken = ACCESS_TOKEN;
$url = "https://api.instagram.com/v1/users/481959735/media/recent/?access_token=".$AccessToken;
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
$Ch = curl_init();
curl_setopt($Ch, CURLOPT_URL, $url);
curl_setopt($Ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Ch, CURLOPT_TIMEOUT, 20);
curl_setopt($Ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($Ch, CURLOPT_SSL_VERIFYPEER, 0);
$Result = curl_exec($Ch);
curl_close($Ch);
$Result = json_decode($Result);
if(isset($Result->data)){
$Data = $Result->data;
for($i=0; $i<count($Data); $i++){
if(empty($Data)){
continue;
}
$LikesSum = $Data[$i]->likes->count; // Get likes total per media
$CommentsSum = $Data[$i]->comments->count; // Get comments total per media
$InstagramId = $Data[$i]->user->id; // Get media instagrammer id
$MediaId = $Data[$i]->id; // Get media id
$data = array(
'instagram_id' => $InstagramId,
'media_id' => $MediaId,
'comments_count' => $CommentsSum,
'likes_count' => $LikesSum,
'created_date' => date(DATE_YYYYMMDDHMS_24),
'status' => '1'
);
$this->db->insert('instagrammer_table', $data);
if($this->db->affected_rows() > 0){
echo "Insert successful";
}else{
echo "Failed to insert record";
}
}
if(isset($Result->pagination->next_url) && !empty($Result->pagination->next_url)){
$next = $Result->pagination->next_url;
$this->User($next);
}else{
$NextUrl = "";
}
}
}

Write Array to File:PHP

I'm trying to write the array $jsonDataInArray to an external csv file. Right now, my file only has the column headers without the data underneath. Could someone help me step through this PHP array, $jsonDataInArray, and write it to an external .csv file?
//set url for pipedrive data being pulled
$api_token="soemToken";
$url = "https://someURL.com;
$ch = curl_init(); //initialize connection with a URL
//check if cURL is enabled or not
if(is_callable('curl_init'))
{
echo "curl_init Enabled";
}
else
{
echo "curl_init Not enabled";
}
echo '<br/><br/><br/><br/><br/><br/>';
curl_setopt($ch, CURLOPT_URL, $url); //fetching URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //return queried data as string
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);//verify certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//check the existence of a common name & verify that it matches the hostname provided
curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/permissingFile.pem");//name of file holding certificates to verify peer with
$json_response = curl_exec($ch);//perform cURL session. Returns ALL of JSON data if sucessful, false if not.
$info = curl_getinfo($ch);//gets array of info about cURL transfer.
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);//gets HTTP message about cURL transfer
if ( $status != 200 )
{
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
//die();
}
curl_close($ch);//close connection with URL
// create an array from the data that is sent back from the API
$response = json_decode($json_response, 1);
// Gets the count of records returned from the api. Used in the for loop to go through response 1 array element at a time.
$count = Count($response['data']);
for ($x=0; $x<$count; $x++)
{
$currentRecord = $response['data'][$x];
$jsonDataInArray = array
(
"id" => $response['data'][$x]['id'],
"user_id" => $response['data'][$x]['user_id']['id'],
"person_id" => $response['data'][$x]['person_id']['value'],
"org_id" => $response['data'][$x]['org_id']['value'],
"stage_id" => $response['data'][$x]['stage_id'],
"title" => $response['data'][$x]['title'],
"value" => $response['data'][$x]['value'],
"currency" => $response['data'][$x]['currency'],
"add_time" => $response['data'][$x]['add_time'],
"update_time" => $response['data'][$x]['update_time'],
"stage_change_time" => $response['data'][$x]['stage_change_time'],
"active" => $response['data'][$x]['active'],
"deleted" => $response['data'][$x]['deleted'],
"status" => $response['data'][$x]['status'],
);
ksort($currentRecord);
}
$test_array = $response['data'][0];//test_array = first row of data
if($startPos == 0){
$fp = fopen('cacheDeals3.csv', 'w');
fputcsv($fp, array_keys($response['data'][0]));
}else{
$fp = fopen('cacheDeals3.csv', 'a');
}
foreach ($jsonDataInArray as $fields)
{
fputcsv($fp, $fields);
}
$jsonDataInArray is being overwritten on every iteration of the for loop, therefore fputcsv is being passed a string as the $field parameter rather than an array.
You need to append a new array to $jsonDataInArray each time, change
$jsonDataInArray = array
to
$jsonDataInArray[] = array

decision making based on json array

I am working on an payment gateway API to process refunds.
On successful operation, the API returns a json array like this
{
"currencyCode" : "GBP",
"amount" : 100,
"originalMerchantRefNum" : "MERCHANTREF12346",
"mode" : "live",
"confirmationNumber" : 1997160616609792,
"authType" : "refund",
"id" : "25TWPTLHRR81AIG1LF"
}
On error the array returned is
{
"error": {
"code": "400",
"message": "Amount exceeds refundable amount"
}
}
I need to decode the json output and then show it to the user. But since the structure of the json array is different in both cases, how do I go arnd parsing the json array, so as to give relevant readable data to the end user.
My code which, does all the talking and fetching data from the gateway processor is given below
<?php
include('lock.php');
$flag=0;
$oid=$_POST['oid'];
if(isset($_POST['amount']))
{
$amount=$_POST['amount'];
$amount = $amount*100;
$flag=1;
}
// generate random number
$merchantref=mt_rand(10,9999999999);
//API Url
$url = 'https://api.netbanx.com/hosted/v1/orders/'.$oid.'/refund';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
if($flag==1)
{
$jsonData = array(
"amount" => $amount,
'merchantRefNum' => $merchantref
);
}
else
{
$jsonData = array(
'merchantRefNum' => $merchantref
);
}
//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("..") //Base 64 encoding and appending Authorization: Basic
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the request
$result = curl_exec($ch);
$jdata=$result;
//decode the json output and store it in a variable
$jfo = json_decode($jdata);
//Handle decision making based on json output
?>
Basically something as simple as:
$response = json_decode(..., true);
if (isset($response['error'])) {
echo 'Sorry, ', $response['error']['message'];
} else {
echo 'Yay!';
}
What exactly you need to check for depends on the possible values the API may return. Most APIs specify something along the lines of "status will be set to 'success' or 'error'", or maybe "if the error key is present, this indicates an error, otherwise a success".

How to setup ios platform through code with apple push notification p12 certificate file?

I want to create an app with ios platform set up from the .p12 file. How do I do that?
This is the method for creating app:
class AppHandler
{
public $USER_AUTH_KEY = 'Insert your key here';
public function create($name, $apns_p12 = null, $apns_p12_password = null, $gcm_key = null, $android_gcm_sender_id = null)
{
$fields = array(
'name' => $name,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
"Authorization: Basic " . $this->USER_AUTH_KEY));
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);
try {
$response = curl_exec($ch);
if (!$response) {
throw new Exception("App wasn't created");
}
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
} finally {
curl_close($ch);
}
$response = json_decode($response, true);
$return = array(
'id' => $response['id'],
'basic_auth_key' => $response['basic_auth_key']
);
return $return;
}
...
And this is the method with 2 ways of getting the insides of .p12 file:
public function getP12($pkcs12, $password = NULL): string
{
/*
// Way 1:
$pkcs12 = file_get_contents($pkcs12);
$encoded = base64_encode($pkcs12);
return $encoded;
*/
// Way 2:
$cert_store = file_get_contents($pkcs12);
if (!$cert_store) {
echo "Error: can't read file.\n";
exit;
}
$pkcs12Read = openssl_pkcs12_read($cert_store, $cert_info, $password);
if ($pkcs12Read) {
$result = base64_encode($cert_info['cert']);
return $result;
} else {
echo "Error: can't read cert.\n";
exit;
}
}
According to onesignal's doc I have to send apns_p12 as my apple push notification p12 certificate file, converted to a string and Base64 encoded.
And I do that this way:
$obj = new AppHandler();
$response = $obj->create('TestName', $obj->getP12('cert.p12', 'password'), 'password')
It creates an app with given name, however, the platform is not set up.
What do you mean by "the platform is not set up"? What error are you getting and where?
By the way, I finally gave up trying code the intricacies of APNS programming and instead went with AWS' Simple Notification Service: https://aws.amazon.com/sns. It handles both Apple and Google notifications by using the API to set up topics and subscribers, plus you can send up to 1 million notifications per month free.
Ok, I got it. I simply needed to add apns_env parameter:
$fields = array(
'name' => $name,
'apns_env' => $apns_env,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
And I should've taken insides of the file and converted them to a string and Base64 encoded like that:
public function getP12($pkcs12): string
{
$apns_12 = base64_encode(file_get_contents($pkcs12));
return $apns_12;
}

Categories