Prestashop webservice create order - php

I'm trying to create API connection to prestashop via webservices
I can create Custommers, Addresses, Carts succesfully
(there is available well known pure documentation about customers CRUD,
it works as expected)
I'm not able to complete new Order:
There is source code fragment
require_once('config.php'); // PS_SHOP_PATH etc.
require_once('PSWebServiceLibrary.php');
try
{
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$opt = array('resource' => 'orders');
$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/orders?schema=blank'));
$xml->children()->children()->id_address_delivery = 1;
$xml->children()->children()->id_address_invoice = 1;
$xml->children()->children()->id_cart = 25;
$xml->children()->children()->id_currency = 1;
$xml->children()->children()->current_state = 1;
$xml->children()->children()->id_lang = 1;
$xml->children()->children()->id_customer = 1;
$xml->children()->children()->id_carrier = 0;
$xml->children()->children()->total_paid = '56973';
$xml->children()->children()->total_paid_real = '56973';
$xml->children()->children()->total_paid_tax_excl = '56973';
$xml->children()->children()->total_paid_tax_incl = '56977';
$xml->children()->children()->total_products = 1338;
$xml->children()->children()->total_products_wt = 1337;
$xml->children()->children()->conversion_rate = '1';
$xml->children()->children()->secure_key = md5('-1');;
$xml->children()->children()->valid = 1;
$xml->children()->children()->module = 'Bankwire';
$xml->children()->children()->payment = 'bankwire';
$xml->children()->children()->current_state = 1;
unset($xml->children()->children()->id);
unset($xml->children()->children()->date_add);
unset($xml->children()->children()->date_upd);
unset($xml->children()->children()->associations);
unset($xml->children()->children()->delivery_date);
unset($xml->children()->children()->invoice_date);
unset($xml->children()->children()->total_discounts_tax_incl);
unset($xml->children()->children()->total_discounts_tax_excl);
$xml = $webService->add(array('resource' => 'orders',
'postXml' => $xml->asXML()
));
$resources = $xml->children()->children();
echo "Successfully added order.".$resources->id;
}
catch (PrestaShopWebserviceException $ex)
{
// Here we are dealing with errors
$trace = $ex->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$ex->getMessage();
}
And there is part. webview log from Fiddler
XML SENT
xml=<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<order>
<id_address_delivery>1</id_address_delivery>
<id_address_invoice>1</id_address_invoice>
<id_cart>25</id_cart>
<id_currency>1</id_currency>
<id_lang>1</id_lang>
<id_customer>1</id_customer>
<id_carrier>0</id_carrier>
<current_state>1</current_state>
<module>Bankwire</module>
<invoice_number/>
<delivery_number/>
<valid>1</valid>
<id_shop_group/>
<id_shop/>
<secure_key>6bb61e3b7bce0931da574d19d1d82c88</secure_key>
<payment>bankwire</payment>
<recyclable/>
<gift/>
<gift_message/>
<mobile_theme/>
<total_discounts/>
<total_paid>56973</total_paid>
<total_paid_tax_incl>56977</total_paid_tax_incl>
<total_paid_tax_excl>56973</total_paid_tax_excl>
<total_paid_real>56973</total_paid_real>
<total_products>1338</total_products>
<total_products_wt>1337</total_products_wt>
<total_shipping/>
<total_shipping_tax_incl/>
<total_shipping_tax_excl/>
<carrier_tax_rate/>
<total_wrapping/>
<total_wrapping_tax_incl/>
<total_wrapping_tax_excl/>
<shipping_number/>
<conversion_rate>1</conversion_rate>
<reference/>
</order>
</prestashop>
RETURN HTTP BODY
Fatal error
Other error
HTTP XML response is not parsable : array ( 0 => LibXMLError::__set_state(array( 'level' => 3, 'code' => 4, 'column' => 1, 'message' => 'Start tag expected, \'<\' not found ', 'file' => '', 'line' => 1, )), )
"Other error" comes from this:
else echo 'Other error<br />'.$ex->getMessage();
PSWebServiceLibrary contains
/** #var array compatible versions of PrestaShop Webservice */
const psCompatibleVersionsMin = '1.4.0.17';
const psCompatibleVersionsMax = '1.5.4.1';
PrestaShop is 1.5.4.0
Any advice?

Problem solved.
1) create Customer (opt.)
2) create Address (opt.)
3) check Products availibility (this is really better...)
4) create Cart with order_rows and with product id's and quantities
5) create Order with this
in all cases required tags should by filled- see /api/object?schema=synopsis
Simply cart should not be empty before create order, its sounds logic
in step by step intearctive process and the same sequence should
be done in "batch" processing via webservices.

For placing order through webservice you need to make some entries directly to db with respect to cart like delivery option in cart table and for discount add entries in ps_cart_cart_rule table then place and order as you were placing.
1. add cart;
2. add discount options with respect to cart.
3. add delivery option with respect to cart.
4. Place order With same cart id.
Code as followed:
foreach ($raw_data['discounts'] as $discount) {
foreach ($raw_data['discounts'] as $discount) {
$sql = "insert into ps_cart_cart_rule values('" . $id['cart'] . "','" . $discount['id_cart_rule'] . "')";
$r = mysql_query($sql, $conn)or die(mysql_error($conn));
}
$sql = "update ps_cart set `delivery_option`='a:1:{i:" . $id['address'] . ";s:3:\"" . $id['carrier'] . ",\";}', `id_carrier`='" . $id['carrier'] . "' where id_cart='" . $id['cart'] . "'";
$r = mysql_query($sql, $conn)or die(mysql_error($conn));
$xml = $webService->get(array('url' => PS_SHOP_PATH . '/api/orders?schema=blank'));
$xml->order->id_customer = $id['customer'];
$xml->order->id_address_delivery = $id['address'];
$xml->order->id_address_invoice = $id['address'];
$xml->order->id_cart = $id['cart'];
$xml->order->id_currency = $id['currency'];
$xml->order->id_lang = $id['lang'];
$xml->order->id_carrier = $id['carrier'];
$xml->order->current_state = "3";
$xml->order->valid = 0;
$xml->order->total_shipping = $raw_data['total_shipping'];
$xml->order->total_shipping_tax_incl = $raw_data['total_shipping'];
$xml->order->total_shipping_tax_excl = $raw_data['total_shipping'];
$xml->order->total_discounts = $raw_data['total_discounts'];
$xml->order->total_discounts_tax_incl = $raw_data['total_discounts'];
$xml->order->total_discounts_tax_excl = $raw_data['total_discounts'];
$xml->order->payment = 'Cash on delivery';
$xml->order->module = 'cashondelivery';
$xml->order->total_products = $raw_data['total_products'];
$xml->order->total_products_wt = $raw_data['total_products'];
$xml->order->total_paid = $raw_data['total_paid'];
$xml->order->total_paid_tax_incl = $raw_data['total_paid'];
$xml->order->total_paid_tax_excl = $raw_data['total_paid'];
$xml->order->total_paid_real = "0";
$xml->order->conversion_rate = '1';
$opt = array('resource' => 'orders');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
$id['order'] = $xml->order->id;
$id['secure_key'] = $xml->order->secure_key;

Following error is because of missing required value in Cart or Order
HTTP XML response is not parsable : array ( 0 => LibXMLError::__set_state(array( 'level' => 3, 'code' => 4, 'column' => 1, 'message' => 'Start tag expected, \'<\' not found ', 'file' => '', 'line' => 1, )), )
In my case id_address_delivery & id_address_invoice where missing in Cart, that's why i was facing this error.
Read more at PrestaShop web service create order errors

If you are getting this Start tag expected, \'<\' not found ', error try to check response which your sending to parse.
This is showing due to improper data that you sending in order or due to xml validation problem.
I also gone through same problem and I solved it by checking what response I am sending to parse method in Prestashop library.

define('DEBUG', true);
define('PS_SHOP_PATH', 'http://.....');
define('PS_WS_AUTH_KEY', '...');
define('FILE_NAME', 'file.xlsx');
require_once('./PSWebServiceLibrary.php');
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
require_once __DIR__.'/src/SimpleXLSX.php';
$newArray = array(); // here we will accumulate grouped data
$dataArray=[];
$product_count=0;
if ( $xlsx = SimpleXLSX::parse(FILE_NAME) ) {
for($i=1; $i < count($xlsx->rows()); $i++){
$id=$xlsx->rows()[$i][0];
$product_id=$xlsx->rows()[$i][96];
if($product_id)
{
if(!isset($dataArray[$id]))
{
$dataArray[$id]["products"][$product_id]= $xlsx->rows()[$i][103];
$dataArray[$id]["price"]=$xlsx->rows()[$i][38];
$dataArray[$id]["product_weight"]=$xlsx->rows()[$i][24];
$dataArray[$id]["id_address_delivery"]=$xlsx->rows()[$i][170];
$dataArray[$id]["id_carrier"]=$xlsx->rows()[$i][172];
$dataArray[$id]["payment_mode"]=$xlsx->rows()[$i][173];
$dataArray[$id]["product_count"]=$product_count;
$dataArray[$id]["currency_code"] = $xlsx->rows()[$i][17];
}
else
{
if(!isset($dataArray[$id]["products"][$product_id]))
{
$dataArray[$id]["products"][$product_id]+= $xlsx->rows()[$i][103];
}
else
{
$dataArray[$id]["products"][$product_id]+= $xlsx->rows()[$i][103];
}
}
}
}
} else {
echo SimpleXLSX::parseError();
}
try{
foreach($dataArray as $key => $value){
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/carts?schema=blank'));
$xml_currency = $webService->get(array('url' => PS_SHOP_PATH.'/api/currencies/?display=full'));
$xml_language = $webService->get(array('url' => PS_SHOP_PATH.'/api/languages?display=full'));
$value['id_language'] = (int)$xml_language->languages->language->id;
$xml->cart->id_customer = $key;
$count = 0;
$value['total_products'] = 0;
foreach($value['products'] as $product_key => $product_value){
$xml->cart->associations->cart_rows->cart_row[$count]->id_product = $product_key;
$xml->cart->associations->cart_rows->cart_row[$count]->quantity = $product_value;
$value['total_products']+= $product_value;
$count++;
}
for($i=0; $i<count($xml_currency->currencies->currency);$i++){
if($xml_currency->currencies->currency[$i]->iso_code == $value['currency_code'])
$value['id_currency'] =(int) $xml_currency->currencies->currency[$i]->id;
}
$xml->cart->id_address_delivery = $value['id_address_delivery'];
$xml->cart->id_address_invoice = $value['id_address_delivery'];
$xml->cart->id_currency = $value['id_currency'];
$xml->cart->id_lang = $value['id_language'];
$xml->cart->id_carrier = $value['id_carrier'];
$opt = array('resource' => 'carts');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
$cart_id = $xml->cart->id;
$xml = $webService->get(array('url' => PS_SHOP_PATH .'/api/orders/?schema=blank'));
$xml->order->id_address_delivery = $value['id_address_delivery'];
$xml->order->id_address_invoice = $value['id_address_delivery'];
$xml->order->id_cart = $cart_id;
$xml->order->id_currency = $value['id_currency'];
$xml->order->id_lang = $value['id_language'];
$xml->order->id_customer = $key;
$xml->order->id_carrier = $value['id_carrier'];
if($value['payment_mode'] == 'Cash on delivery (COD)')
$xml->order->module = 'ps_cashondelivery';
if($value['payment_mode'] == 'Payment by check')
$xml->order->module = 'ps_checkpayment';
$xml->order->payment = $value['payment_mode'];
$xml->order->total_paid = $value['price'];
$xml->order->total_paid_real = $value['price'];
$xml->order->total_products = $value['total_products'];
$xml->order->total_products_wt = $value['product_weight'];
$xml->order->conversion_rate = '1'; // conversion rate is fixed here
$opt = array('resource' => 'orders');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
}
}catch (PrestaShopWebserviceException $e) {
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404)
echo 'Bad ID';
else if ($trace[0]['args'][0] == 401)
echo 'Bad auth key';
else
echo 'Other error<br />'.$e->getMessage();
} catch (PrestaShopWebserviceException $e) {
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$e->getMessage();
}

Related

how to use dreamscape api in nodejs for check domain name

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

square payment form php check customer exists in directory and make payment

Am new to Square Payment Form using PHP and trying to do following steps
Check If customer Exists in Directory
If Customer Does not exist - create new customer and collect CUSTOMER_ID
MAKE PAYMENT & get Payment ID
Couple of time this script worked by started getting Maximum execution time of 30 seconds exceeded AND created multiple customer entries in directory and payment failed
PS : am using GOTO to loop and ENV file for credentials
Any help will be appreciated in advance
print_r($_POST);
$booknow = $_POST;
require 'vendor/autoload.php';
use Dotenv\Dotenv;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;
use Square\Exceptions\ApiException;
use Square\SquareClient;
use Square\Environment;
use SquareConnect\ApiClient;
use Square\Models\CreateCustomerRequest;
$idem = UUID::v4();
$sname = explode(' ', $_POST["cname"]);
$sname0 = $sname[0];
$sname1 = $sname[1];
$cphone = $_POST["cphone"];
//$cphone = '9848848450';
$cemailid = $_POST["cemailid"];
$ifare = ($_POST["ifare"] * 100);
$xnote = $_POST["note"];
//echo '<br><br>fare : ' . $ifare . '<br><br>';
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();
$upper_case_environment = strtoupper(getenv('ENVIRONMENT'));
$access_token = getenv($upper_case_environment.'_ACCESS_TOKEN');
//print_r($access_token);
//echo '<br><br><br>';
$client = new SquareClient([
'accessToken' => $access_token,
'environment' => getenv('ENVIRONMENT')
]);
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log('Received a non-POST request');
echo 'Request not allowed';
http_response_code(405);
return;
}
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
echo 'Invalid card data';
http_response_code(422);
return;
}
searchCustomers: ///search customers
$phone_number = new \Square\Models\CustomerTextFilter();
$phone_number->setFuzzy($cphone);
$filter = new \Square\Models\CustomerFilter();
$filter->setPhoneNumber($phone_number);
$query = new \Square\Models\CustomerQuery();
$query->setFilter($filter);
$body = new \Square\Models\SearchCustomersRequest();
$body->setQuery($query);
$api_response = $client->getCustomersApi()->searchCustomers($body);
if ($api_response->isSuccess()) {
$rmn = $api_response->getBody();
$stx = json_decode($rmn,true);
echo '<br><br>';
echo '# of arrays : ' . count($stx);
if(count($stx) != 0){
//echo '<br><br>';
$cust_id = $stx["customers"][0]["id"];
//echo "Customer ID : " . $cust_id;
goto makePayment;
//goto end;
} else {
//echo 'user do not exists';
/// new customer - start
$body1 = new \Square\Models\CreateCustomerRequest();
$body1->setIdempotencyKey($idem);
$body1->setGivenName($sname0);
$body1->setFamilyName($sname1);
$body1->setEmailAddress($cemailid);
$body1->setPhoneNumber($cphone);
$api_response = $client->getCustomersApi()->createCustomer($body1);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
goto searchCustomers;
} else {
$errors = $api_response->getErrors();
}
/// new customer - end
}
} else {
echo '<br><br>sorry not found!<bR><br>';
}
goto end;
makePayment:
$amount_money = new \Square\Models\Money();
$amount_money->setAmount($ifare);
$amount_money->setCurrency('USD');
$body = new \Square\Models\CreatePaymentRequest(
'cnon:card-nonce-ok',
$idem,
$amount_money
);
$body->setCustomerId($cust_id);
$body->setNote($xnote);
$api_response = $client->getPaymentsApi()->createPayment($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$srt = json_encode($result);
echo '<br><br>';
echo "PAYEMNT SUCCESSUFLL <BR><br><br>";
//print_r($srt);
goto end;
} else {
$errors = $api_response->getErrors();
echo 'payment FAILEDDDDDDDDDD';
}
goto end;
end:

GAPI.LOL API throwing unknown error while opening Game

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

PrestaShop: Can't create order with web service

I'm trying to create an order using the web service on another web page i have. I'm running the latest version of PrestaShop 1.7. It's really basic, just entering ID of product and quantity. This is my first serious task and i'm struggling to make this work, which it still doesn't. The code i will soon show can create a cart, but it can not create the order for some reason.
Code:
try {
/*
Creating new cart
*/
$xml = $webService->get( array( 'url' => PS_SHOP_PATH .'/api/carts?schema=blank' ) );
// Required
$xml->cart->id_currency = 1;
$xml->cart->id_lang = 1;
foreach($_SESSION['vezimas'] as $i => $vezimas) {
$xml->cart->associations->cart_rows->cart_row[$i]->id_product = $vezimas['product_id'];
$xml->cart->associations->cart_rows->cart_row[$i]->quantity = $vezimas['qty'];
}
// Adding the new cart
$opt = array( 'resource' => 'carts' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );
$id_cart = $xml->cart->id;
/*
Creating Order
*/
// Getting the structure of an order
$xml = $webService->get(array('url' => PS_SHOP_PATH .'/api/orders/?schema=blank'));
// Required
$xml->order->id_address_delivery = 6; // Customer address
$xml->order->id_address_invoice = 6;
$xml->order->id_cart = $id_cart;
$xml->order->id_currency = 1;
$xml->order->id_lang = 1;
$xml->order->id_customer = 2;
$xml->order->id_carrier = 1;
$xml->order->module = 'ps_checkpayment';
$xml->order->payment = 'Payments by check';
$xml->order->total_paid = 0;
$xml->order->total_paid_real = 0;
$xml->order->total_products = $_SESSION['prekesNum'];
$xml->order->total_products_wt = 0;
$xml->order->conversion_rate = 1;
// Others
$xml->order->valid = 1;
// Order Row. Required
foreach($_SESSION['vezimas'] as $i => $vezimas) {
$xml->order->associations->order_rows->order_row[0]->product_id = $vezimas['product_id'];
$xml->order->associations->order_rows->order_row[0]->product_quantity = $vezimas['qty'];
}
// Creating the order
$opt = array( 'resource' => 'orders' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );
$id_order = $xml->order->id;
} catch (PrestaShopWebserviceException $e) {
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$e->getMessage();
}
I get a fatal error in Debug, and this on the page:
Other error
HTTP XML response is not parsable: array ( 0 => LibXMLError::__set_state(array( 'level' => 3, 'code' => 4, 'column' => 1, 'message' => 'Start tag expected, \'<\' not found ', 'file' => '', 'line' => 1, )), )
Added some more field and a secure key to my cart code then it worked fine.

Error #520009 - Account is restricted

I get a 520009 error (Account xx#xx.com is restricted) when trying to make a parallel payment. My code worked fine using the sandbox but I switched to the live endpoint and it began failing. The account in question is a valid paypal account and I am using "feespayer=SENDER". Am I missing something? Shouldn't the pay call go through even if the payee is a basic account? Why would this occur?
Here is my code for reference
function deposit($config) {
try {
if (isset($config['return_url']))
$this->return_url = $config['return_url'];
else
return 'Return URL should be set';
if (isset($config['return_url']))
$this->cancel_url = $config['cancel_url'];
else
return 'Cancel URL should be set';
if (isset($config['email']))
$this->sender_email = $config['email'];
else
return 'Email should be defined';
if (isset($config['amount']))
$this->amount = $config['amount'];
else
return 'Amount should be defined';
$returnURL = $this->return_url;
$cancelURL = $this->cancel_url;
$currencyCode = 'USD';
$memo = 'Deposit to ' . $this->ci->config->item('site_name');
$feesPayer = 'SENDER';
$payRequest = new PayRequest();
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = $cancelURL;
$payRequest->returnUrl = $returnURL;
$payRequest->clientDetails = new ClientDetailsType();
$payRequest->clientDetails->applicationId = $this->ci->config->item('application_id');
$payRequest->clientDetails->deviceId = $this->ci->config->item('device_id');
$payRequest->clientDetails->ipAddress = $this->ci->input->ip_address();
$payRequest->currencyCode = $currencyCode;
//$payRequest->senderEmail = $this->sender_email;
$payRequest->requestEnvelope = new RequestEnvelope();
$payRequest->requestEnvelope->errorLanguage = "en_US";
$receivers = array();
$receiver = new receiver();
$receiver->email = $this->ci->config->item('moneyfan_account');
$receiver->amount = $this->amount;
$receiver->primary = 'false';
$receivers[] = $receiver;
$payRequest->receiverList = $receivers;
$payRequest->feesPayer = $feesPayer;
$payRequest->memo = $memo;
$ap = new AdaptivePayments();
$response = $ap->Pay($payRequest);
if (strtoupper($ap->isSuccess) == 'FAILURE') {
$this->ci->session->set_userdata('FAULTMSG', $ap->getLastError());
return json_encode(array('status' => 'false', 'msg' => $ap->getLastError()->error->errorId .' : '. $ap->getLastError()->error->message));
//redirect(site_url('home/api_error'));
} else {
$this->ci->session->set_userdata('payKey', $response->payKey);
if ($response->paymentExecStatus == "COMPLETED") {
redirect($returnURL);
} else {
$token = $response->payKey;
$payPalURL = PAYPAL_REDIRECT_URL . '_ap-payment&paykey=' . $token;
return json_encode(array('status' => 'true', 'msg' => $payPalURL));
//header("Location: " . $payPalURL);
}
}
} catch (Exception $ex) {
$fault = new FaultMessage();
$errorData = new ErrorData();
$errorData->errorId = $ex->getFile();
$errorData->message = $ex->getMessage();
$fault->error = $errorData;
$this->ci->session->set_userdata('FAULTMSG', $fault);
redirect(site_url('home/api_error'));
}
}
No! You cannot do that with a basic account.
For API to work you need to have a VERIFIED Business Account.
In their API it says:
NOTE:
The application owner must have a PayPal Business account.
There are two sources of reference for the PayPal API:
cms.paypal.com pages like the one referenced by Mihai Iorga, and
www.x.com pages like this one:
https://www.x.com/developers/paypal/documentation-tools/going-live-with-your-application
On x.com, it says you must have a verified business account, even though it is unclear from cms.paypal.com that this is the case.

Categories