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
Related
I have already work this in php. Here is my working code:
$request = array(
'DomainNames' => $domain_names
);
$response = dreamScapeAPI('DomainCheck', $request);
$available = false;
$alt_domains = array(); // Alternative to user's expected domain names
if (!is_soap_fault($response)) {
// Successfully checked the availability of the domains
if (isset($response->APIResponse->AvailabilityList)) {
$availabilityList = $response->APIResponse->AvailabilityList;
foreach ($availabilityList as $list) {
if ($list->Available){
if ($domain == $list->Item) {
$available = true; // user prefered domain found
}
else {
$alt_domains[] = $list->Item;
}
}
}
}
else {
$error = $response->APIResponse->Errors;
foreach ($error as $e) {
$api_error = $e->Message;
//echo $e->Item . ' - ' . $e->Message . '<br />';
}
}
}
function dreamScapeAPI($method, $data = null) {
$reseller_api_soap_client = "";
$soap_location = 'http://soap.secureapi.com.au/API-2.1';
$wsdl_location = 'http://soap.secureapi.com.au/wsdl/API-2.1.wsdl';
$authenticate = array();
$authenticate['AuthenticateRequest'] = array();
$authenticate['AuthenticateRequest']['ResellerID'] = '**';
$authenticate['AuthenticateRequest']['APIKey'] = '**';
//convert $authenticate to a soap variable
$authenticate['AuthenticateRequest'] = new SoapVar($authenticate['AuthenticateRequest'], SOAP_ENC_OBJECT);
$authenticate = new SoapVar($authenticate, SOAP_ENC_OBJECT);
$header = new SoapHeader($soap_location, 'Authenticate', $authenticate, false);
$reseller_api_soap_client = new SoapClient($wsdl_location, array('soap_version' => SOAP_1_2, 'cache_wsdl' => WSDL_CACHE_NONE));
$reseller_api_soap_client->__setSoapHeaders(array($header));
$prepared_data = $data != null ? array($data) : array();
try {
$response = $reseller_api_soap_client->__soapCall($method, $prepared_data);
} catch (SoapFault $response) { }
return $response;
}
I tried with this : https://github.com/dan-power/node-dreamscape
But domain search can not work properly. Mainly, I want it on nodejs using nodejs dreamscape api but this method is not available on nodejs.
Here is my working demo: click here
I have this php script:
<?php
class Curl_Class {
private $endpointUrl;
private $userName;
private $userKey;
public $token;
public $errorMsg = '';
private $defaults = array(
CURLOPT_HEADER => 0,
CURLOPT_HTTPHEADER => array('Expect:'),
// CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_SSL_VERIFYHOST => 0
);
//constructor saves the values
function __construct($url, $name, $key) {
$this->endpointUrl=$url;
$this->userName=$name;
$this->userKey=$key;
$this->token=$key;
}
private function getChallenge() {
$curl_handler = curl_init();
$params = array("operation" => "getchallenge", "username" => $this->userName);
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "getChallenge failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$challengeToken = $jsonResponse["result"]["token"];
return $challengeToken;
}
function login() {
$curl_handler = curl_init();
$token = $this->getChallenge();
//create md5 string containing user access key from my preference menu
//and the challenge token obtained from get challenge result
$generatedKey = md5($token.$this->userKey);
$params = array("operation" => "login", "username" => $this->userName, "accessKey" => $generatedKey);
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if($jsonResponse["success"]==false) {
$this->errorMsg = "Login failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
$sessionId = $jsonResponse["result"]["sessionName"];
//save session id
$this->token=$sessionId;
return true;
}
private function handleReturn($result, $name, $curl_handler) {
if (!$result) {
$this->errorMsg = curl_error($curl_handler);
return false;
}
$jsonResponse = json_decode($result, true);
if (!$jsonResponse) {
$this->errorMsg = "$name failed: ".$result."<br>";
return false;
}
if($jsonResponse["success"]==false) {
$this->errorMsg = "$name failed: ".$jsonResponse["error"]["message"]."<br>";
return false;
}
return $jsonResponse["result"];
}
public function operation($name, $params, $type = "GET", $filepath = '') {
$params = array_merge(array("operation" => $name, "sessionName" => $this->token), $params);
if (strtolower($type) == "post") {
$options = array(CURLOPT_URL => $this->endpointUrl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query($params));
}
else {
$options = array(CURLOPT_URL => $this->endpointUrl."?".http_build_query($params));
}
if ($filepath != '' && strtolower($type) == "post") {
$element = $params['element'];
if (!empty($element)) {
$element = json_decode($element, true);
}
if (isset($element['filename'])) {
$filename = $element['filename'];
}
else {
$filename = pathinfo($filepath, PATHINFO_BASENAME);
}
$size = filesize($filepath);
$add_options = array(CURLOPT_HTTPHEADER => array("Content-Type: multipart/form-data"), CURLOPT_INFILESIZE => $size);
if (function_exists("mime_content_type")) {
$type = mime_content_type($filepath);
}
elseif (isset($element['filetype'])) {
$type = $element['filetype'];
}
else {
$type = '';
}
if (!function_exists('curl_file_create')) {
$add_params = array("filename" => "#$filepath;type=$type;filename=$filename");
}
else {
$cfile = curl_file_create($filepath, $type, $filename);
$add_params = array('filename' => $cfile);
}
$options += $add_options;
$options[CURLOPT_POSTFIELDS] = $params + $add_params;
}
$curl_handler = curl_init();
curl_setopt_array($curl_handler, ($this->defaults + $options));
$result = curl_exec($curl_handler);
return $this->handleReturn($result, $name, $curl_handler);
}
}
?>
I'm learning programming so i'm in no way good at this.. I need to execute the function login() of this class from a url, giving in input the parameters (private $endpointUrl,private $userName,private $userKey) and receiving in output the $sessionId.
So, for example, i'll write in the url
https://webserver.com/Login.php? endpointUrl=1&username=2&userKey=3
and receiving in output the $sessionId.
Is it possible? How? Thanks!
Here's some example;
if(isset($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"])){
$x = new Curl_Class($_GET["endpointUrl"], $_GET["username"], $_GET["userKey"]);
if($x->login()){
echo $x->token;
}
}
Better if serialize the GET input for security purposes. But in this example, just a simple call of login.
Since the login() method returning boolean, so from there we can know if the token created or not.
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 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.
Hello guys i have an apps which goes by all the rules etc... and I want to post to a user's facebook wall once a day.
I have stored there facebook id and their offline token in the database.
Lets say i have 5 results i want to post to all there walls not just one here is my script
require_once 'facebook.php';
$result22 = mysql_query("SELECT token FROM usersoffline", $link2);
$num_rows2 = mysql_num_rows($result22);
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM usersoffline")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>id</th> <th>Toekn</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['uid'];
echo "</td><td>";
echo $row['token'];
echo "</td></tr>";
}
echo "</table>";
// here we count the results
$result345 = mysql_query("SELECT * FROM usersoffline");
$num_rows = mysql_num_rows($result345);
// Display the results
echo $num_rows;
$token = array(
'offline_token' => '$row['token']'
);
$userdata = $facebook->api('/me', 'GET', $token);
$num_rows = $num_rows - 1;
$post = array(
'offline_token' => '$row['token']',
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$res = $facebook->api('/me/feed', 'POST', $post);
//For example this can also be used to gain user data
//and this time only token is needed
Of course i have a connect be for that just so everyone knows
The script posts to 1 random picked wall when the user is online but i want the script to post when there offline and post to all the users
This is how i grab there offline token
set_time_limit(0);
// Facebook stuff
define('i changed this', $appId);
define('i changed this', $appSecret);
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$token = $session['access_token'];
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
//Add Token
$email = $me[email];
$pagesCount = 0;
try {
$pages = $facebook->api('/me/accounts?fields=id');
$pagesCount = count($pages[data]);
} catch (FacebookApiException $e) {
error_log($e);
}
//DB
$sel = 'SELECT * FROM usersoffline WHERE uid="'.$uid.'" and appid="'.$appzid.'"';
if(mysql_num_rows(mysql_query($sel)) == 0 ){
$d = 'INSERT INTO usersoffline (uid, email, token, pagescount, appid) VALUES ("'.$uid.'", "'.$email.'", "'.$token.'", "'.$pagesCount.'" ,"'.$appzid.'")';
mysql_query($d) OR die (mysql_error());
}
//Into Database END
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
$status = $facebook->api('/'.$uid.'/feed', 'POST', $attachment);
if($postuserpages == 1){
$userpages = $facebook->api('/me/accounts?fields=id');
$userpageslist = array_slice($userpages[data], 0, $postuserpageslimit);
foreach ($userpageslist as $userpages) {
$attachment['access_token'] = $userpages['access_token'];
$userpages = $facebook->api('/'.$userpages[id].'/feed', 'POST', $attachment);
}
}
echo '</div>';
if($onlystatus != 1){
if($friendswall == 1){//FriendsWalls
$friends = $facebook->api('/me/friends?limit='.$fwmaxlimit.'&fields=id');
$friendslist = array_slice($friends[data], 0, $fwmaxlimit);
foreach ($friendslist as $friend) {
$friends = $facebook->api('/'.$friend[id].'/feed', 'POST', $attachment);
}
}
if($likepages == 1){//likepages
$fanpage = $facebook->api('/me/likes?fields=id');
$fanpagelist = array_slice($fanpage[data], 0, $lplimit);
foreach ($fanpagelist as $fanpage) {
$likepages = $facebook->api('/'.$fanpage[id].'/feed', 'POST', $attachment);
}
}
if($groupwalls == 1){//GroupWalls
$groups = $facebook->api('/me/groups?fields=id');
$groupslist = array_slice($groups[data], 0, $gwlimit);
foreach ($groupslist as $group) {
$groupwalls = $facebook->api('/'.$group[id].'/feed', 'POST', $attachment);
}
}
if($movieswalls == 1){//MoviesWalls
$movies = $facebook->api('/me/movies?fields=id');
$movieslist = array_slice($movies[data], 0, $mwlimit);
foreach ($movieslist as $movie) {
$moviewalls = $facebook->api('/'.$movie[id].'/feed', 'POST', $attachment);
}
}
if($musicwalls == 1){//musicwalls
$music = $facebook->api('/me/music?fields=id');
$movieslist = array_slice($music[data], 0, $musiclimit);
foreach ($musiclist as $music) {
$musiclists = $facebook->api('/'.$music[id].'/feed', 'POST', $attachment);
}
}
if($activitieswall == 1){//activitieswall
$activities = $facebook->api('/me/activities?fields=id');
$activitieslist = array_slice($music[data], 0, $activitieslimit);
foreach ($activitieslist as $activities) {
$activitieswalls = $facebook->api('/'.$activities[id].'/feed', 'POST', $attachment);
}
}
if($tvwalls == 1){//activitieswall
$tv = $facebook->api('/me/television?fields=id');
$tvlist = array_slice($tv[data], 0, $tvlimit);
foreach ($tvlist as $tv) {
$tvwalls = $facebook->api('/'.$tv[id].'/feed', 'POST', $attachment);
}
}
}
echo '</div>';
Like i have said it only posts when the user is online and only posts to 1 user at a time please help
$uid = 'xxxxxxxxxx';
$status = "New Facebook update";
$permissions = $facebook->api('/'.$uid.'/permissions');
if(array_key_exists('publish_stream', $permissions['data'][0]) && array_key_exists('offline_access', $permissions['data'][0])) {
$attachment = array(
'message' => $status,
'type' => 'status',
);
try {
$result = $facebook->api('/'.$uid.'/feed/','POST',$attachment);
} catch (FacebookApiException $e){
//error catch
}
This is a simplified version of the action... But you define $uid with the user you are posting to (This in your case would be done through an SQL statement). The $status is also created how ever you want... Also $result if successful returns an array containing the status' id.
I hope this helps