I have a table on an Invitation. I am passing the data in json format from postman.
I want to send many invitations at a time. So I want to insert multiple invitations.
How can I do this?
I have created a single invitation.
Invitaion :
class Invitation
{
private $sender_id,$date,$invitee_no,$status;
function Invitation($sender_id,$date,$invitee_no,$status)
{
$this->sender_id = $sender_id;
$this->date= $date;
$this->invitee_no = $invitee_no;
$this->status = $status;
}
function sendInvite()
{
$database = new Database(ContactsConstants::DBHOST,ContactsConstants::DBUSER,ContactsConstants::DBPASS,ContactsConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("select * from Invitation where invitee_no =?");
$stmt->execute(array($this->invitee_no));
$rows = $stmt->rowCount();
if($rows > 0)
{
$response = array("status"=>-3,"message"=>"Invitation exists.");
return $response;
}
$stmt = $dbConnection->prepare("insert into Invitation(date,invitee_no,status) values(?,?,?)");
$stmt->execute(array($this->date, $this->invitee_no, $this->status));
$rows = $stmt->rowCount();
$Id = $dbConnection->lastInsertId();
$stmt = $dbConnection->prepare("select * from Invitation where sender_id=?");
$stmt->execute(array($Id));
$invitation = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
return $response;
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
return $response;
}
}
}
sendInvite.php
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');
require 'Invitation.php';
$jsonText = file_get_contents('php://input');
if(empty($jsonText))
{
$response = array("status"=>-2,"message"=>"Empty request");
die(json_encode($response));
}
$json = json_decode($jsonText);
$date= $json -> date;
$invitee_no = $json -> invitee_no;
$status = $json -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response = $invitation->sendInvite();
echo(json_encode($response));
?>
Input from postman:
{
"date" : "12/08/2016",
"invitee_no" : "5258",
"status" : "1"
}
Output:
{
"status": 1,
"message": "Invitation sent.",
"Invitation:": [
{
"sender_id": "29",
"date": "12/08/2016",
"invitee_no": "5259",
"status": "1"
}
]
}
EDIT:
In Send Invite() function:
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
echo(json_encode($response));
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
echo(json_encode($response));
}
In senInvite.php file :
foreach ($json as $jsn) {
foreach($jsn as $j)
{
$date= $j -> date;
$invitee_no = $j -> invitee_no;
$status = $j -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response = $invitation->sendInvite();
var_dump($response);
die();
echo(json_encode($response));
}
}
var dump:
{"status":-3,"message":"Invitation exists.","invitee_no":"5856"}array(3) {
["status"]=>
int(-3)
["message"]=>
string(18) "Invitation exists."
["invitee_no"]=>
string(4) "5856"
}
Gives syntax error: unexpeted 'S'
I want to accept this as json array and insert into the table all the records.
Can anyone help please? Thank you..
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');
require 'Invitation.php';
$jsonText = file_get_contents('php://input');
if(empty($jsonText))
{
$response = array("status"=>-2,"message"=>"Empty request");
die(json_encode($response));
}
$response = array();
$json = json_decode($jsonText);
foreach ($json as $jsn) {
foreach($jsn as $j)
{
$date= $j -> date;
$invitee_no = $j -> invitee_no;
$status = $j -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response[] = $invitation->sendInvite();
}
}
echo(json_encode($response));
?>
I have used foreach for array.
Related
I am integrating gapi.lol API into a website and the examples are in core PHP and so I had to rewrite them to Laravel because it is the framework the website is using. The API has no support team and so there is no one I can ask a question when need be. I did everything as instructed, however, the problem comes when opening a single game, it throws an unknown error!
The following is the guidance on their website on how to integrate the API.
Importand when a player wins EGT jackpot, Our api server sends writeBet api call with game ID 2500 and your api server should answer with success message
Global jackpot will sends the id of the game player playing.
EXAMPLE
return $apiresult = array(
"status" => "success",
"error" => '',
"login" => ExampleAccount,
"balance" => PlayerBalance,
);
#1 Create users table (you can use your existing table)
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`score` bigint(20) DEFAULT '0',
`callback_key` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ext` (`callback_key`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
#2 Create table user_bets (save bet/wins)
-- ----------------------------
-- Table structure for user_bets
-- ----------------------------
DROP TABLE IF EXISTS `user_bets`;
CREATE TABLE `user_bets` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`in` bigint(20) DEFAULT '0',
`out` bigint(20) DEFAULT '0',
`user_id` bigint(20) DEFAULT NULL,
`date` datetime DEFAULT '1970-01-01 00:00:01',
`game_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=49 DEFAULT CHARSET=latin1;
#3 Create wallet
This is php example you can use any language you want.
if you use your own table do not forget to change the fields on mysql querys
header('Access-Control-Allow-Headers: *'); // This is only for test your wallet
header('Access-Control-Allow-Origin: *'); // This is only for test your wallet
header('Access-Control-Allow-Methods: POST'); // This is only for test your wallet
header('Access-Control-Max-Age: 1000'); // This is only for test your wallet
$db_host = "localhost"; // CHANGE THIS LINE
$db_name = "database"; // CHANGE THIS LINE
$db_user = "root"; // CHANGE THIS LINE
$db_password = "password"; // CHANGE THIS LINE
function sqlsafe($s)
{
global $conn;
$str = strval($s);
return $conn->real_escape_string($str);
}
$inputJSON = file_get_contents('php://input');
if ($inputJSON != '') {
$input = json_decode($inputJSON, TRUE); //convert JSON into array
if (count($input) != '') {
foreach ($input as $name => $value) {
$_POST[$name] = $value;
}
}
} else {
$apiresult = array(
"status" => "fail",
"error" => "101"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$conn = new mysqli($db_host, $db_user, $db_password, $db_name);
if ($conn->connect_error) {
$apiresult = array(
"status" => "fail",
"error" => $conn->connect_error
);
echo json_encode($apiresult);
exit();
}
$cmd = $_POST['cmd'];
$login = sqlsafe($_POST['login']);
if(isset($_POST['gameId'])){
$gameId = $_POST['gameId'];
}
$balance = '1000';
$operationId = '100';
$key = sqlsafe($_POST['key']);
switch ($cmd) {
case 'getBalance':
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
if ($result) {
if ($result->num_rows > 0) {
$userfound = true;
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$apiresult = array(
"status" => "success",
"error" => "",
"login" => $login,
"balance" => $balance
);
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found1"
);
echo json_encode($apiresult);
exit();
}
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found2"
);
echo json_encode($apiresult);
exit();
}
if (!$userfound) {
$apiresult = array(
"status" => "fail",
"error" => "user_not_found3"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
break;
case 'writeBet':
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$winLose = $_POST['winLose'];
$bet = $_POST['bet'];
$out = $winLose + $bet;
$gameId = $_POST['gameId'];
if ($balance < $bet) {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$winLose = (int)floor($winLose * 100 + 0.00001);
$sql = "update `users` set `score` = (`score` + ($winLose)) where (`score`+($winLose)) >= 0 and `id`='$login' and callback_key='$key'";
//writeLog($sql);
$result = $conn->query($sql);
if ($result) {
$bet = (int)floor($bet * 100 + 0.00001);
$out = (int)floor($out * 100 + 0.00001);
$sql = "INSERT INTO user_bets set `in` =$bet, `out`=$out, game_id = $gameId, date=now(), user_id = $login";
$result = $conn->query($sql);
//echo $result;
$sql = "select `score` from `users` where `id`='$login' and callback_key='$key'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$balance = floatval($row['score']) / 100.00;
$apiresult = array(
"status" => "success",
"error" => '',
"login" => $login,
"balance" => $balance,
"operationId" => $operationId
);
} else {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance " . $conn->error
);
}
break;
}
$response = json_encode($apiresult);
echo $response;
#4 Create play page
require_once('lib/ApiClient.php'); //class for api calls
//AMATIC API VARIABLES
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_ID = 'API ID'; // CHANGE THIS LINE
$API_KEY = 'API KEY'; // CHANGE THIS LINE
$GAME_URL = 'https://play.gapi.lol/play/';
//YOUR API VARIABLES
$CALLBACK_URL = 'http://yourdomain.com/wallet.php'; // CHANGE THIS LINE URL FROM wallet.php yourdomain.com/wallet.php
$CALLBACK_KEY = '12345'; //change to api key of your wallet api
$parentid = "walletshop"; //change this to Hall ID on your server the user belongs to
$userid = "1"; // user from wallet API
//GAME INVIROMENT VARIABLES
$game = "arisingphoenix";// You can get all valid games with API 'action'=> 'getgames'
$lang = "en"; // Valid values: "en","de","es","ru","tr","cz","gr","ee"
$exiturl = "back.html"; // url to go to when player clicks exit. Your menu url for example.
if(isset($_GET['game']))
$game = $_GET['game'];
//PREPARE API REQUEST
$params = array(
'action' => 'inituser',
'api_id' => $API_ID,
'hash' => $userid,
'parenthash' => $parentid,
'callbackurl' => $CALLBACK_URL,
'callbackkey' => $CALLBACK_KEY
);
//print_r($params);
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
if($resjson===false)
{
echo 'ERROR:'.$client->lasterror;
}
else
{
$resarray = json_decode($resjson,true);
if($resarray['success']=='true') //API CALL WAS SUCCESSFUL
{
echo '
<iframe src="'.$GAME_URL.'?game='.$game.'&hash='.$userid.'&api_id='.$API_ID.'&lang='.$lang.'&exit='.$exiturl.'"
style="border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%" allowfullscreen>
<iframe>';
}
else
{
echo 'error occured:'.$resarray['error'];
}
}
//ApiClient.php
class ApiClient {
public $apiurl;
public $apikey;
public $lasterror;
public function __construct($url = '', $key = '')
{
$this->apiurl = $url;
$this->apikey = $key;
$this->lasterror = '';
}
function SendData($params)
{
$this->lasterror = '';
//CHECK FOR ERRORS
if($this->apikey=='')
{
$this->lasterror = "API KEY NOT SET";
return false;
}
if($this->apiurl=='')
{
$this->lasterror = "API URL NOT SET";
return false;
}
if(count($params)==0)
{
$this->lasterror = "PARAMETERS NOT SET";
return false;
}
if(!$this->is_assoc($params))
{
$this->lasterror = "WRONG PARAMETERS VARIABLE. MUST BE ASSOCIATIVE ARRAY";
return false;
}
//END CHECKING FOR ERRORS
$joinparams = '';
$rand = md5(time());
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$enc_val = urlencode($val);
$post_params[] = $key.'='. $enc_val;
$joinparams = $joinparams.$enc_val;
}
$post_params[] = 'callid'.'='. $rand; //add random unique call identifier
$joinparams = $joinparams.$rand; //add it to sign
$sign = hash_hmac("sha1",$joinparams,$this->apikey);
$post_string = implode('&', $post_params).'&sign='.$sign;
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiurl);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'curl');
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
if($result==false)
{
$this->lasterror = curl_error($ch);
return false;
}
}
catch (Exception $e)
{
$this->lasterror = "Exception :".$e->getMessage();
return false;
}
curl_close($ch);
return $result;
}
function is_assoc(array $array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
}
This is how I rewrote the same in Laravel:
WalletController.php:
<?php
namespace App\Http\Controllers;
use App\Wallet;
use App\User_bet;
use App\User;
use App\GameUrl;
use App\Classes\ApiClient;
use Illuminate\Http\Request;
class WalletController extends Controller
{
public function wallet(Request $request)
{
$inputJSON = file_get_contents('php://input');
if ($inputJSON != '') {
$input = json_decode($inputJSON, TRUE); //convert JSON into array
if (count($input) != '') {
foreach ($input as $name => $value) {
$request->$name = $value;
}
}
} else {
$apiresult = array(
"status" => "fail",
"error" => "101"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$cmd = $request->cmd;
$login = $request->login;
if($request->gameId){
$gameId = $request->gameId;
}
$balance = '1000';
$operationId = '100';
$key = $request->key;
switch ($cmd) {
case 'getBalance':
$user = auth()->user();
if ($user) {
$userfound = true;
$balance = floatval($user->score) / 100.00;
$apiresult = array(
"status" => "success",
"error" => "",
"login" => $login,
"balance" => $balance
);
} else {
$userfound = false;
$apiresult = array(
"status" => "fail",
"error" => "user_not_found1"
);
echo json_encode($apiresult);
exit();
}
if (!$userfound) {
$apiresult = array(
"status" => "fail",
"error" => "user_not_found3"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
break;
case 'writeBet':
$user = auth()->user();
$balance = floatval($user->score) / 100.00;
$winLose = $request->winLose;
$bet = $request->bet;
$out = $winLose + $bet;
$gameId = $request->gameId;
if ($balance < $bet) {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance"
);
$response = json_encode($apiresult);
echo $response;
exit();
}
$winLose = (int)floor($winLose * 100 + 0.00001);
$user = auth()->user();
$user->score = $user->score +($winLose);
if ($user->save()) {
$bet = (int)floor($bet * 100 + 0.00001);
$out = (int)floor($out * 100 + 0.00001);
$user_bet = new User_bet();
$user_bet->in = $bet;
$user_bet->out = $out;
$user_bet->game_id = $gameId;
$user_bet->date = now();
$user_bet->user_id = $login;
$user_bet->save();
$user = auth()->user();
$balance = floatval($user->score) / 100.00;
$apiresult = array(
"status" => "success",
"error" => '',
"login" => $login,
"balance" => $balance,
"operationId" => $operationId
);
} else {
$apiresult = array(
"status" => "fail",
"error" => "fail_balance " . $conn->error
);
}
break;
}
}
public function home(){
return view('slot.home');
}
public function getgames()
{
$user = auth()->user();
if($user){
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_KEY = 'LP8CGiNnTTyNxhb3BGxMcLMWdSOMGQRJ';
$params = array(
'api_id' => 'eErNZwJ36onh9qoq5sOek2zN8yWZZePe',
'action' => 'getgames',
'callbackurl' => 'http://127.0.0.1:8000/api/slot/wallet ',
'callbackkey' => 'SDFSD8FHSHD0N');
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
// dd($resjson);
$games =\json_decode($resjson);
return response()-> json($games);
}else{
$error = "User not found".$url;
return response()->json($error);
}
}
public function getUrl($gameName)
{
//AMATIC API VARIABLES
$API_URL = 'https://play.gapi.lol/api/games/post/';
$API_ID = 'eErNZwJ36onh9qoq5sOek2zN8yWZZePe'; // API_ID
$API_KEY = 'LP8CGiNnTTyNxhb3BGxMcLMWdSOMGQRJ'; // API_KEY
$GAME_URL = 'https://play.gapi.lol/play/';
//YOUR API VARIABLES
$CALLBACK_URL = 'http://127.0.0.1:8000/api/slot/wallet'; // CHANGE THIS LINE URL FROM wallet.php yourdomain.com/wallet.php
$CALLBACK_KEY = '12345'; //change to api key of your wallet api
$parentid = "walletshop"; //change this to Hall ID on your server the user belongs to
$userid = auth()->user()->id;
//GAME INVIROMENT VARIABLES
$game = $gameName;// You can get all valid games with API 'action'=> 'getgames'
$lang = "en"; // Valid values: "en","de","es","ru","tr","cz","gr","ee"
$exiturl = "http://127.0.0.1:8000/api/slot/home"; // url to go to when player clicks exit. Your menu url for example.
//PREPARE API REQUEST
$params = array(
'action' => 'inituser',
'api_id' => $API_ID,
'hash' => $userid,
'parenthash' => $parentid,
'callbackurl' => $CALLBACK_URL,
'callbackkey' => $CALLBACK_KEY
);
//print_r($params);
$client = new ApiClient($API_URL,$API_KEY);
$resjson = $client->SendData($params);
if($resjson===false)
{
$error = 'ERROR:'.$client->lasterror;
return \response()->json($error);
}
else
{
$resarray = json_decode($resjson,true);
if($resarray['success']=='true') //API CALL WAS SUCCESSFUL
{
$URL =
$GAME_URL.'?game='.$game.'&hash='.$userid.'&api_id='.$API_ID.'&lang='.$lang.'&exit='.$exiturl;
$gameUrl = new GameUrl();
$gameUrl->url = $URL;
$gameUrl->user_id = \auth()->user()->id;
if($gameUrl->save()){
return response()->json($URL);
}
}
else
{
$error = 'error occured:'.$resarray['error'];
return \response()->json($error);
}
}
}
public function play()
{
$user = auth()->user()->id;
$gameUrl = GameUrl::where("user_id", $user)->latest()->first();
$link= $gameUrl->url;
return view('slot.play', compact('link'));
}
}
I am handling it in a way that I list all the games from the API on the home page when someone clicks on any single game, I generate the game URL in the getURL method in wallets controller, the redirect the user to that page. It works well but when someone opens the game, it throws an error in the process of opening.
```Game opening```
Showing CONTINUE button:
Error on localhost
I'm trying to edit a JSON file using php, I've set up a little ReactJS app has form elements.
My JSON is as follows
[
{
"id": 1,
"Client": "client 1",
"Project": "project 1",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-1"
},
{
"id": 2,
"Client": "client 2",
"Project": "project 2",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-2"
},
{
"id": 3,
"Client": "client 3",
"Project": "project 3",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-3"
}
]
So far i have code to create a new "project" at the end of the file. My PHP is as follows
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$clientName = $_POST['clientName'];
$ProjectName = $_POST['projectName'];
$url = strtolower($_POST['url']);
$date = date('Y/m/d H:i:s');
$message = "";
$url = '../json/projects.json';
if( file_exists($url) )
if(file_exists('../json/projects.json'))
{
$current_data = file_get_contents('../json/projects.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => count($array_data) + 1,
'Client' => $clientName,
'Project' => $ProjectName,
'StartDate' => $date,
'CompletedDate' => "",
'projectUrl' => $projectFileName + ".json"
);
$array_data[] = $extra;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents('../json/projects.json', $final_data))
{
$message = "sent";
}
else
{
$message = "notSent";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
What i can figure out is how to edit lets say "CompletedDate" value to todays date with a click of the button.
I have an hidden input field on my page that has the project ID in, so what I'm after is helping getting that id, matching it to the JSON, then editing the completed date that matches the ID.
This PHP will fire using ajax so i can pass the ID pretty easy.
Using similar code to what you already use, you can update the relevant data by using the ID as the index into the decoded JSON file. As ID 1 will be the [0] element of the array, update the [$id-1] element with the date...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$id = 2; // Fetch as appropriate
$date = date('Y/m/d H:i:s');
$url = '../json/projects.json';
if( file_exists($url) )
{
$current_data = file_get_contents($url);
$array_data = json_decode($current_data, true);
$array_data[$id-1]['CompletedDate'] = $date;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents($url, $final_data))
{
$message = "updated";
}
else
{
$message = "notUpdated";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
You may need to tweak some of the bits - especially how the ID is picked up ($_GET?) and any messages you want.
I've also updated the code to make more consistent use of $url as opposed to hard coding it in a few places.
I am use mgp25/Instagram-API
How can l get my instagram posts with the likes of a particular user?
My code:
set_time_limit(0);
date_default_timezone_set('UTC');
require __DIR__.'/vendor/autoload.php';
$username = 'myInstagramUsername';
$password = 'myInstagramPassword';
$debug = false;
$truncatedDebug = false;
$ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
try {
$ig->login($username, $password);
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
exit(0);
}
try {
$userId = $ig->people->getUserIdForName($username);
$act = json_encode($ig->people->getRecentActivityInbox(), true);
???????
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
}
Worked
set_time_limit(0);
date_default_timezone_set('UTC');
require __DIR__.'/vendor/autoload.php';
$username = 'username';
$password = 'password';
$debug = false;
$truncatedDebug = false;
$ig = new \InstagramAPI\Instagram($debug, $truncatedDebug);
try {
$ig->login($username, $password);
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
exit(0);
}
try {
$posts = [];
$comments = [];
$userId = $ig->people->getUserIdForName($username);
$maxId = null;
$response = $ig->timeline->getUserFeed($userId, $maxId);
foreach ($response->getItems() as $item) {
foreach($item->getLikers($item->getId()) as $h){
$posts[] = ['id' => $item->getId(), 'username' => $h->username];
}
foreach($ig->media->getComments($item->getId()) as $v){
if(count($v->comments) > 0){
foreach($v->comments as $c){
$comments[] = ['id' => $item->getId(), 'username' => $c->user->username, 'text' => $c->text];
}
}
}
}
print_r($posts);
print_r($comments);
} catch (\Exception $e) {
echo 'Something went wrong: '.$e->getMessage()."\n";
}
Try looping through each item of your profile then get the likes and find the username. Then if the item has a like by that user put it in an item array like so:
// Get the UserPK ID for "natgeo" (National Geographic).
$userId = $ig->people->getUserIdForName('natgeo');
// Starting at "null" means starting at the first page.
$maxId = null;
do {
$response = $ig->timeline->getUserFeed($userId, $maxId);
// In this example we're simply printing the IDs of this page's items.
foreach ($response->getItems() as $item) {
//loop through likes as u can see in [source 1][1] there is some method called 'getLikers()' which u can call on a media object.
foreach($item->getMedia()->getLikers() as $h){
// here do some if with if response user == username
}
}
source 1:https://github.com/mgp25/Instagram-API/blob/master/src/Request/Media.php
source 2:https://github.com/mgp25/Instagram-API/tree/master/examples
source 3:https://github.com/mgp25/Instagram-API/blob/e66186f14b9124cc82fe309c98f5acf2eba6104d/src/Response/MediaLikersResponse.php
By reading the source files this could work i havent tested it yet.
for new version of mgp25 this code work fine
POST UPDATED
$likes = [];
$comments = [];
$userId = $ig->people->getUserIdForName($username);
$maxId = null;
$response = $ig->timeline->getUserFeed($userId, $maxId);
$posts = $response->jsonSerialize();
foreach ($response->getItems() as $item) {
$likers = $ig->media->getLikers($item->getId());
if ($likers != null) {
foreach ($likers->getUsers() as $h) {
$likes[] = ['id' => $item->getId(), 'username' => $h->getUsername()];
}
}
$commentsList = $ig->media->getComments($item->getId());
if ($commentsList != null) {
foreach ($commentsList->getComments() as $c) {
$comments[] = ['id' => $item->getId(), 'username' => $c->getUser()->getUsername(), 'text' => $c->getText()];
}
}
}
updated reference link
I am using usaEpay for my mobile app. I was using my friend's server and there was no problem.
Then I rented a server for my own. switched the backend to the new server. I am using the exact same code. I implemented rapid SSL to my site. But I cannot make a payment.
This is the error;
Error reading from card processing gateway.
Unsupported SSL protocol version
My php api is the same as this; https://github.com/usaepay/usaepay-php/blob/master/usaepay.php
this is my payOrder.php class
require('connector.php');
include ('phpseclib/Crypt/RSA.php');
include ('usaepay/usaepay.php');
$request = json_decode($HTTP_RAW_POST_DATA, true);
$token = $request['token'];
$orderid = $request['orderid'];
$ccInfo = base64_decode($request['ccinfo']);
$address = $request['address'];
if(strlen($out_plain) >= 25) {
$query = "SELECT * FROM xxxx_order WHERE order_id = $orderid";
$result = mysql_query($query);
$order = mysql_fetch_assoc($result);
$total = $order['order_total'];
$creditcard = explode("||", $out_plain);
$ccnumber = $creditcard[0];
$cvvnumber = $creditcard[1];
$cctype = $creditcard[2];
$ccmonth = $creditcard[3];
$ccyear = $creditcard[4];
$ccdate = $ccmonth.$ccyear;
$ccname = $creditcard[5];
$address = explode("||", $address);
$street = $address[0];
$city = $address[1];
$state = $address[2];
$zip = $address[3];
$name = $address[4];
$umcommand = "cc:sale" ;
$umkey = "mykey" ;
$pin = "mypin";
$tran=new umTransaction;
$tran->key = "mytrkey";
$tran->pin = "mypin";
$tran->usesandbox = false;
$tran->testmode = 0;
$tran->command = "cc:sale";
$tran->card = $ccnumber;
$tran->exp = $ccdate;
$tran->amount = $total;
$tran->invoice = $orderid;
$tran->cardholder = $ccname;
$tran->street = $street;
$tran->zip = $zip;
$tran->description = "App sale";
$tran->cvv2 = $cvvnumber;
flush();
if($tran->Process()) {
$auth = $tran->authcode;
$refnum = $tran->refnum;
$response = "$auth---$refnum";
$query = "UPDATE `mydb` SET `order_status`= 2, UMresponse =
$check = false;
$count = 0;
do {
$check = mysql_query($query);
$count++;
} while ($check == false && $count < 50);
array_push($arr, array("status" => "success", "request" => "check", "order_status" => "success"));
} else {
$tranresult = $tran->result;
$tranerror = $tran->error;
$trancurl = "";
if(#$tran->curlerror) $trancurl = $tran->curlerror;
$response = "$tranresult---$tranerror---$trancurl";
$query = "UPDATE `mydb` SET `order_status`= 4, UMresponse = '$response' WHERE order_id = $orderid";
$check = false;
$count = 0;
do {
$check = mysql_query($query);
$count++;
} while ($check == false && $count < 50);
array_push($arr, array("status" => "success", "request" => "check", "order_status" => "declined"));
}
/*
$hashseed = mktime (); // mktime returns the current time in seconds since epoch.
$hashdata = $umcommand . ":" . $pin . ":" . $total . ":" . $orderid . ":" . $hashseed ;
$hash = md5 ( $hashdata );
$umhash = "m/$hashseed/$hash/y";
$fields = array(`enter code here`
"UMkey" => urlencode($umkey),
"UMredir" => urlencode("myurl"),
"UMinvoice" => urlencode($orderid),
"UMamount" => urlencode($total),
"UMname" => urlencode($ccname),
"UMstreet" => urlencode($street),
"city" => urlencode($city),
"City" => urlencode($city),
"state" => urlencode($state),
"State" => urlencode($state),
"UMzip" => urlencode($zip),
"cardtype" => urlencode($cctype),
"UMcard" => urlencode($ccnumber),
"UMexpir" => urlencode($ccdate),
"UMcommand" => urlencode("cc:sale"),
"UMhash" => $umhash,
"UMechofields" => "yes",
"OrderRef" => $orderid
);
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$url = "https://www.usaepay.com/gate.php";
// $fields = "UMkey=".urlencode($umkey)."&UMredir=".urlencode("myurl**strong text**")."&UMinvoice=$orderid&UMamount=".urlencode($total)."&UMname=".urlencode($ccname)."&UMstreet=".urlencode($street)."&city=".urlencode($city)."&state=".urlencode($state)."&UMzip=".urlencode($zip)."&cardtype=".urlencode($cctype)."&UMcard=".urlencode($ccnumber)."&UMexpir=".urlencode($ccdate)."&UMcommand=".urlencode("cc:sale");
// array_push($arr, array("url" => $url, "fields" => $fields_string));
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
if($result == true) {
array_push($arr, array("status" => "success", "request" => "send", "msg" => "Payment request sent"));
}
else {
array_push($arr, array("status" => "error", "request" => "send", "msg" => "Failed to connect to the payment system"));
}
//close connection
curl_close($ch);
*/
} else {
array_push($arr, array("status" => "error", "request" => "send", "msg" => "Decryption failure, please check fields before submission"));
} else {
array_push($arr, array("status" => "error", "request" => "send", "msg" => "User token not verified"));
}
header('Content-Type: application/json');
echo json_encode($arr);
Any help would be overly appreciated. What is my problem ?
I think the error message said it clearly that your communication with payment gateway is rejected or refused due to unsupported SSL version, you should check your server setting and compare with your friend's server. BTW, looking at your PHP code, do you know that mysql extension has been deprecated since PHP v5.5.0 and total removed from PHP 7? I'd suggest that you read PHP The right way about the Database part and the php.net documentation.
I'm editing file php for telegram bot. When I test on telegram, it shows no response at all. On PHP command line, it said:
Warning:
file_get_contents(https://api.telegram.org/bottoken/sendMessage):
failed to open
stream: HTTP request failed! HTTP/1.1 400 Bad Request in G:\xampp\htdocs\xbot\file.php on
line 39
And on line 39:
$result = file_get_contents(request_url('sendMessage'), false, $context);
But, it works when I change function create_response to this:
function create_response($text)
{
$conn = mysqli_connect("localhost","root","admintma","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
//$hasil = '';
if (mysqli_num_rows($cari) > 0) {
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"]. ": " . $row["ayattext"]. ". ";
var_dump($hasil);
}
} else {
$hasil = "0 results";
}
return $hasil;
mysqli_close($conn);
}
But it only shows just last result while on php command line show complete result:
string(157) "Value1"
string(219) "Value2"
string(462) "Value3"
string(555) "Value4"
string(246) "Value5"
{
"ok": true,
"result": {
"message_id": 197,
"from": {
"id": 107653xxx,
"first_name": "x_bot",
"username": "x_bot"
},
"chat": {
"id": 2887198,
"first_name": "xxx",
"username": "xxx"
},
"date": 1437240345,
"reply_to_message": {
"message_id": 196,
"from": {
"id": 2887xxx,
"first_name": "xxx",
"username": "xxx"
},
"chat": {
"id": 2887xxx,
"first_name": "xxx",
"username": "xxx"
},
"date": 1437240342,
"text": "mengetahuinya"
},
"text": "Value5"
}
}
I'm confused, how to solve this problem? Thanks in advance.
Here's the complete code:
<?php
include("token.php");
//include("db.php");
function request_url($method)
{
global $TOKEN;
return "https://api.telegram.org/bot" . $TOKEN . "/". $method;
}
function get_updates($offset)
{
$url = request_url("getUpdates")."?offset=".$offset;
$resp = file_get_contents($url);
$result = json_decode($resp, true);
if ($result["ok"]==1)
return $result["result"];
return array();
}
function send_reply($chatid, $msgid, $text)
{
$data = array(
'chat_id' => $chatid,
'text' => $text,
'reply_to_message_id' => $msgid
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents(request_url('sendMessage'), false, $context);
print_r($result);
}
function create_response($text)
{
$conn = mysqli_connect("localhost","root","xxx","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
//$hasil = '';
if (mysqli_num_rows($cari) > 0) {
$hasil = array();
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"] . ": " . $row["ayattext"] . ". ";
//var_dump($hasil);
}
} else {
$hasil = "0 results";
}
return $hasil;
mysqli_close($conn);
}
function process_message($message)
{
$updateid = $message["update_id"];
$message_data = $message["message"];
if (isset($message_data["text"])) {
$chatid = $message_data["chat"]["id"];
$message_id = $message_data["message_id"];
$text = $message_data["text"];
$response = create_response($text);
send_reply($chatid, $message_id, $response);
}
return $updateid;
}
function process_one()
{
$update_id = 0;
if (file_exists("last_update_id")) {
$update_id = (int)file_get_contents("last_update_id");
}
$updates = get_updates($update_id);
foreach ($updates as $message)
{
$update_id = process_message($message);
}
file_put_contents("last_update_id", $update_id + 1);
}
while (true) {
process_one();
}
?>
The problem is that your function process_message() expects create_response() to return a string, and the code that doesn't work is returning an array when there are results and a string when there are no results. It's best if it returns always the same type of data.
To fix it, change the create_response() function to always return an array, and have process_message() to use it however it needs, i.e., transform it in a string.
By the way, your return command must be the last command executed in the function. You have mysqli_close($conn); after it, which is never executed if return is above it.
So, those two functions become:
function create_response($text)
{
$conn = mysqli_connect("localhost","root","xxx","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
$hasil = array();
if (mysqli_num_rows($cari) > 0) {
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"] . ": " . $row["ayattext"] . ". ";
}
}
mysqli_close($conn);
return $hasil;
}
function process_message($message)
{
$updateid = $message["update_id"];
$message_data = $message["message"];
if (isset($message_data["text"])) {
$chatid = $message_data["chat"]["id"];
$message_id = $message_data["message_id"];
$text = $message_data["text"];
$responseArr = create_response($text);
if (count($responseArr) > 0) {
$response = implode(". ", $responseArr) . ".";
} else {
$response = "0 results";
}
send_reply($chatid, $message_id, $response);
}
return $updateid;
}