Paypal transaction insertin '0' as value - php

have this paypal page which is working fine only when paypal posts back its not inserting my correct value (By this I mean its inserting '0'), please take a look...
<?php
require 'config.inc.php';
$p = new Paypal();
if(isset($_GET['period']))
{
$allowedPeriods = array("1000", "5000", "10000", "20000");
if(!in_array($_GET['period'], $allowedPeriods))
{
die("Allowed periods are '1000', '5000', '10000', '20000'");
}
if(!$usersClass->checkLoggedIn())
{
die("You must be logged in");
}
$prices = array( "1000" => 10, "5000" => 30, "10000" => 50, "20000" => 85 );
$this_script = "http://".$_SERVER['HTTP_HOST']."/paypal.php?act=";
$p->add_field('business', PAYPAL_EMAIL_ADDRESS);
$p->add_field('return', $this_script.'success');
$p->add_field('cancel_return', $this_script.'cancel');
$p->add_field('notify_url', $this_script.'ipn');
$p->add_field('item_name', 'Credits');
$p->add_field('cmd', '_xclick');
$p->add_field('amount', $prices[$_GET['period']]);
$p->add_field('custom', $usersClass->userID()."||".$_POST['period']);
$p->add_field('rm', '2');
$p->add_field('currency_code','GBP');
$p->submit_paypal_post();
}
if(isset($_GET['act'])) {
switch ($_GET['act']) {
case "cancel": print "Order was canceled!";
break;
case "success":
print "If payment was successfully received you should be on the top!";
break;
case "ipn": if ($p->validate_ipn()) {
$custom = $_POST['custom'];
$explode = explode("||", $custom);
$userid = (int) $explode[0];
$days = $explode[1];
$daysArray = array(10 => 1000, 30 => 5000, 50 => 10000, 85 => 20000 );
$days = $daysArray[$days];
$tillDate = $days;
mysql_query("insert into `featured` values (null, '$userid', '$tillDate')")
}
break;
}
}
?>

I suggest you set error_reporting(E_ALL) and do a post yourself on the ipn script to test it out. 0 could also mean FALSE before using (int) in front of it so it's crucial that you open all errors and see the response yourself.

Related

Simultaneous execution of many requests

I have an Instagram robot site
My program for each user makes a task that must be run every minute
Now my server has encountered a problem
I want my plan to be optimized
i am 427 user and my script for user create one cron jobs and repeat every minutes
all cron jobs send this formats
mysite.com/api/cron/[userpagename]
and my functions cron this code
/****************************************/
/* CRON */
/****************************************/
public function cron($type = ""){
$schedule_list = $this->db->select('activities.*, account.username, account.password, account.proxy, account.default_proxy')
->from($this->tb_activities." as activities")
->join($this->tb_accounts." as account", "activities.account = account.id")
->where("account.username = '{$type}' AND activities.status = 1 AND activities.time <= '".NOW."' AND account.status = 1")->order_by("time", "asc")->limit(2,0)->get()->result();
if(!empty($schedule_list)){
foreach ($schedule_list as $key => $schedule) {
if(!permission("instagram/activity", $schedule->uid)){
$this->db->delete($this->tb_activities, array("id" => $schedule->id));
$this->db->update($this->tb_activities, array("status" => 0, array("id" => $pid)));
$this->db->delete('instagram_activities_log', "uid = '{$schedule->uid}'");
$this->db->delete('instagram_activities', "uid = '{$schedule->uid}'");
$this->db->delete('instagram_accounts', "uid = '{$schedule->uid}'");
$this->deleteLineInFile("./cron.txt",$schedule->username);
exec('crontab ./cron.txt');
$this->model->send_email(get_option("email_renewal_reminders_subject", ""), get_option("email_renewal_reminders_content", ""), $schedule->uid);
}
$action = $schedule->action;
echo $schedule->action;
$mainId = $schedule->pid;
$settings = json_decode($schedule->data);
$speed = get_value($settings, "speed");
$next = get_time_next_schedule($schedule->settings, $speed->$action);
$stop = $this->stop_activity($mainId, $schedule->action , $schedule);
print_r(get_random_numbers(20));
if($stop){ break; }
if($next->task != 0){
$schedule->number = $next->task;
$proxy_data = get_proxy($this->tb_accounts, $schedule->proxy, $schedule);
try {
$ig = new InstagramAPI($schedule->username, $schedule->password, $proxy_data->use);
$result = $ig->activity->process($schedule);
//print_r($result);
if(is_array($result) || is_object($result)){
$this->save_log($schedule, $result);
$next->numbers = get_action_left($next->numbers, $result, $next->task);
}
} catch (Exception $e) {
print_r($e->getMessage());
$mess = Instagram_Get_Message($e->getMessage());
//ig_update_setting($schedule->action."_block", $e->getMessage(), $mainId);
if(strpos($mess, "This action was blocked")){
$next->numbers = get_random_numbers(0);
ig_update_setting($schedule->action."_block", "", $mainId);
}
else{
$next->numbers = get_action_left($next->numbers, array(), $next->task);
}
}
}
$this->db->update(INSTAGRAM_ACTIVITIES, array(
"time" => date("Y-m-d H:i:s", strtotime(NOW) + $next->minute*60),
"settings" => json_encode($next->numbers),
"changed" => date("Y-m-d H:i:s", strtotime(NOW) + $next->minute*60)
),
array("id" => $schedule->id)
);
}
}else{
echo "No activity";
}
I want to send all these requests together without error or failure

Square API - invalid character 'C' looking for beginning of value

I am using Square Charge API, and following is my request object for a test card -
I am using Square provided PHP client to connect to the API. And I am receiving following response for "Charge" endpoint -
[HTTP/1.1 400 Bad Request] {"errors":[{"category":"INVALID_REQUEST_ERROR","code":"BAD_REQUEST","detail":"invalid character 'C' looking for beginning of value (line 1, character 1)"}]}
Following is my code in PHP -
public function chargeCustomerCard($userId, $custId, $cardId, $note, $billingAddres, $amount, $idempotencyKey){
$billingAddrRequest = array("address_line_1" => $billingAddres->addr1, "address_line_2" => $billingAddres->addr2, "locality" => $billingAddres->city, "administrative_district_level_1" => $billingAddres->state, "postal_code" => $billingAddres->zip, "country" => $billingAddres->country);
$billingAddressReq = new \SquareConnect\Model\Address($billingAddrRequest);
$moneyRequest = array("amount" => $amount, "currency" => "USD");
$money = new \SquareConnect\Model\Money($moneyRequest);
$request = array("idempotency_key" => $idempotencyKey, "customer_id" => $custId, "customer_card_id" => $cardId, "delay_capture" => false, "amount_money" => $money, "billing_address" => $billingAddressReq, "note" => $note, "reference_id" => $userId);
$charge = new \SquareConnect\Model\ChargeRequest($request);
$response = null;
try{
$charge_api = new \SquareConnect\Api\TransactionsApi();
$response = $charge_api->charge($this->authtoken, $this->locationId, $charge);
if($response != null && count($response->getErrors()) == 0){
$transaction = $response->getTransaction();
$data = array();
$data['transactionId'] = $transaction->getId();
$data['created'] = $transaction->getCreatedAt();
$data['referenceId'] = $transaction->getReferenceId(); //this should be equal to userid
$tender = $transaction->getTenders()[0];
$data['tenderId'] = $tender->getId();
$data['note'] = $tender->getNote();
$data['amount'] = ($tender->getAmountMoney()->getAmount())/100;
$data['currency'] = $tender->getAmountMoney()->getCurrency();
$processingFee = $tender->getProcessingFeeMoney();
if(isset($processingFee) && !empty($processingFee)){
$data['processingFee'] = $tender->getProcessingFeeMoney()->getAmount();
}else{
$data['processingFee'] = 0;
}
$data['tendertype'] = $tender->getType();
$data['cardStatus'] = $tender->getCardDetails()->getStatus();
$data['cardBrand'] = $tender->getCardDetails()->getCard()->getCardBrand();
$data['cardLast4'] = $tender->getCardDetails()->getCard()->getLast4();
$data['idempotencyKey'] = $idempotencyKey;
$data['customerPayId'] = $custId;
$data['customerCardId'] = $cardId;
return $this->generateReturnData(PAY_API_SUCCESS, '', $data);
}else{
return $this->generateReturnData(PAY_API_FAIL, '', $response->getErrors());
}
}catch(Exception $e) {
return $e->getMessage();
}
}
Can someone please point out to me what am I doing wrong here. I am really stuck here. Other API endpoints are working fine, such as, Create Customer, Create Customer Card API endpoints, using the same approach and same PHP client provided by square.
PS - this is on sandbox

Randomised Greeting Function - PHP

So, I have created a script in PHP that sets a greeting dependent on date and time. The code checks for any seasonal events, and if there are none, it checks the time and assigns the appropriate greeting. My issue that I am having is:
I have set the value to check if the time is past 18:00, if it is past this time, it should set an evening greeting. My issue is that if I change the php if argument value to a time in the future, it still keeps the greeting as an evening greeting. What could be wrong?
Here is my code:
$morningGreetings = array(
1 => "Good morning",
2 => "Morning",
);
$standardGreetings = array(
1 => "Hello",
2 => "Howdy",
3 => "Hiya",
4 => "Greetings",
5 => "Great to see you",
6 => "Hi there",
7 => "Hi",
8 => "Good day",
);
$eveningGreetings = array(
1 => "Evening",
2 => "Good evening",
);
$seasonalGreetings = array(
1 => "Merry Christmas",
2 => "Happy New Year",
);
$eventGreetings = array(
1 => "Happy Birthday",
);
if (date("d m") != strtotime("25 12")) {
if (date("d m") != strtotime("0 0")) {
if (date("G i") <= strtotime("18 00")) {
if (date("G i") <= strtotime("09 00")) {
$sizeOfArray = sizeof($standardGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $standardGreetings[$greetingValue];
} else {
$sizeOfArray = sizeof($morningGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $morningGreetings[$greetingValue];
}
} else {
$sizeOfArray = sizeof($eveningGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $eveningGreetings[$greetingValue];
}
} else {
$greeting = $seasonalGreetings[2];
}
} else {
$greeting = $seasonalGreetings[1];
}
Maybe something like this:
EDIT
$seasonalGreetingA=array();
$seasonalGreetingA[]=array('dayBegin'=>30,'monthBegin'=>12,'dayEnd'=>31,'monthEnd'=>12,'text'=>'Happy New Year');
$seasonalGreetingA[]=array('dayBegin'=>1,'monthBegin'=>1,'dayEnd'=>2,'monthEnd'=>1,'text'=>'Happy New Year');
$seasonalGreetingA[]=array('dayBegin'=>21,'monthBegin'=>6,'dayEnd'=>23,'monthEnd'=>9,'text'=>'Happy Spring');
$seasonalGreetingA[]=array('dayBegin'=>12,'monthBegin'=>11,'dayEnd'=>23,'monthEnd'=>11,'text'=>'Happy All');
$dateGreetingA=array();
$dateGreetingA[]=array('date'=>'2014-11-09','text'=>'Happy Birthday');
$timeGreetingA=array();
$timeGreetingA[]=array('timeBegin'=>8,'timeEnd'=>12,'text'=>'Morning');
$timeGreetingA[]=array('timeBegin'=>8,'timeEnd'=>12,'text'=>'Good morning');
$timeGreetingA[]=array('timeBegin'=>18,'timeEnd'=>23,'text'=>'Evening');
$timeGreetingA[]=array('timeBegin'=>18,'timeEnd'=>23,'text'=>'Good evening');
$timeGreetingA[]=array('timeBegin'=>23,'timeEnd'=>24,'text'=>'Time out');
$timeGreetingA[]=array('timeBegin'=>13,'timeEnd'=>18,'text'=>'Good afternoon');
$standardGreetingA[]=array();
$standardGreetingA[]=array('text'=>'Hello');
$standardGreetingA[]=array('text'=>'Howdy');
$standardGreetingA[]=array('text'=>'Hi');
$txtGreeting='';
$date=date('Y-m-d');
if($txtGreeting=='')
if(count($dateGreetingA)>0)
foreach($dateGreetingA as $dgA)
{
if($dgA['date']==$date)
{
$txtGreeting=$dgA['text'];
break;
}
}
$d=(int)date('d');
$m=(int)date('m');
if($txtGreeting=='')
if(count($seasonalGreetingA)>0)
foreach($seasonalGreetingA as $sgA)
{
$d1=$sgA['dayBegin'];
$m1=$sgA['monthBegin'];
$d2=$sgA['dayEnd'];
$m2=$sgA['monthEnd'];
//echo $m1.' >= '.$m.' <= '.$m2.'<br />';
if($m>=$m1 and $m<=$m2)
if($d>=$d1 and $d<=$d2)
$txtGreeting=$sgA['text'];
}
$time=(int)date('H');
if($txtGreeting=='')
if(count($timeGreetingA)>0)
foreach($timeGreetingA as $tgA)
{
if($time>=$tgA['timeBegin'] and $time<= $tgA['timeEnd'])
{
$txtGreeting=$tgA['text'];
break;
}
}
if($txtGreeting=='')
if(count($standardGreetingA)>0)
{
$ind=rand(0,count($standardGreetingA)-1);
if(isset($standardGreetingA[$ind])) $txtGreeting=$standardGreetingA[$ind]['text'];
}
echo $txtGreeting;
exit;

cakephp and Webhooks

Im new to cakephp and have implemented the Webshop Solution Snipcart. When an order is processed by snipcart they send a webhook to our site. The webhook looks like this according to their documentation:
{
eventName: "order:completed",
mode: "Live",
createdOn: "2013-07-04T04:18:44.5538768Z",
content: {
token: "22808196-0eff-4a6e-b136-3e4d628b3cf5",
creationDate: "2013-07-03T19:08:28.993Z",
modificationDate: "2013-07-04T04:18:42.73Z",
status: "Processed",
paymentMethod: "CreditCard",
email: "customer#snipcart.com",
cardHolderName: "Nicolas Cage",
billingAddressName: "Nicolas Cage",
billingAddressCompanyName: "Company name",
billingAddressAddress1: "888 The street",
billingAddressAddress2: "",
billingAddressCity: "Québec",
billingAddressCountry: "CA",
billingAddressProvince: "QC",
billingAddressPostalCode: "G1G 1G1",
billingAddressPhone: "(888) 888-8888",
shippingAddressName: "Nicolas Cage",
shippingAddressCompanyName: "Company name",
shippingAddressAddress1: "888 The street",
shippingAddressAddress2: "",
shippingAddressCity: "Québec",
shippingAddressCountry: "CA",
shippingAddressProvince: "QC",
shippingAddressPostalCode: "G1G 1G1",
shippingAddressPhone: "(888) 888-8888",
shippingAddressSameAsBilling: true,
finalGrandTotal: 310.00,
shippingAddressComplete: true,
creditCardLast4Digits: "4242",
shippingFees: 10.00,
shippingMethod: "Livraison",
items: [{
uniqueId: "eb4c9dae-e725-4dad-b7ae-a5e48097c831",
token: "22808196-0eff-4a6e-b136-3e4d628b3cf5",
id: "1",
name: "Movie",
price: 300.00,
originalPrice: 300.00,
quantity: 1,
url: "https://snipcart.com",
weight: 10.00,
description: "Something",
image: "http://placecage.com/50/50",
customFieldsJson: "[]",
stackable: true,
maxQuantity: null,
totalPrice: 300.0000,
totalWeight: 10.00
}],
subtotal: 610.0000,
totalWeight: 20.00,
hasPromocode: false,
promocodes: [],
willBePaidLater: false
}
}
And the consume the webhooks looks like this:
<?php
$json = file_get_contents('php://input');
$body = json_decode($json, true);
if (is_null($body) or !isset($body['eventName'])) {
// When something goes wrong, return an invalid status code
// such as 400 BadRequest.
header('HTTP/1.1 400 Bad Request');
return;
}
switch ($body['eventName']) {
case 'order:completed':
// This is an order:completed event
// do what needs to be done here.
break;
}
// Return a valid status code such as 200 OK.
header('HTTP/1.1 200 OK');
My question is, how do I do this in CakePHP version 2.4. I've been looking for days now on the internet for a solution, but tho i'm inexperienced I can't find a proper solution.
Solved it:
public function webhooks(){
//check if POST
if ($this->request->is('post')) {
//Allow raw POST's
$url = 'php://input';
//decode
$json = json_decode(file_get_contents($url), true);
if (is_null($json) or !isset($json['eventName'])) {
// When something goes wrong, return an invalid status code
// such as 400 BadRequest.
header('HTTP/1.1 400 Bad Request');
return;
}
//do whatever needs to be done, in this case remove the quantity ordered from the stock in db.
switch ($json['eventName']) {
case 'order:completed':
$id = $json['content']['items'][0]['id'];
$quantity = $json['content']['items'][0]['quantity'];
$query = $this->Shop->findById($id, 'Shop.stock');
$stock = $query['Shop']['stock'];
$stock = $stock - $quantity;
$this->Shop->updateAll(array('Shop.stock' => $stock), array('Shop.id' => $id));
break;
}
header('HTTP/1.1 200 OK');
}
}
the only thing I would add to your answer is a few more "cake" ways of doing some things.
public function webhooks(){
//check if POST
if ($this->request->is('post') || $this->request->is('put')) {
//Allow raw POST's
$url = 'php://input';
//decode
$json = json_decode(file_get_contents($url), true);
if (empty($json) or empty($json['eventName'])) {
throw new BadRequestException('Invalid JSON Information');
}
//do whatever needs to be done, in this case remove the quantity ordered from the stock in db.
switch ($json['eventName']) {
case 'order:completed':
$id = $json['content']['items'][0]['id'];
$quantity = $json['content']['items'][0]['quantity'];
$shop = $this->Shop->find('first', array(
'conditions' => array(
'Shop.id' => $id,
),
'fields' => array(
'Shop.stock',
),
));
if (empty($shop)) {
throw new NotFoundException(__('Invalid Shop Content'));
}
$stock = $shop['Shop']['stock'];
$stock = $stock - $quantity;
$this->Shop->id = $id;
$this->Shop->saveField('stock', $stock);
break;
}

mysql to json using php. Nested objects

Good Afternoon,
I am trying to get these results into arrays in PHP so that I can encode them into json objects and send them to the client. The results of the query look like this:
id name hours cat status
3bf JFK Int 24 pass open
3bf JFK Int 24 std closed
3bf JFK Int 24 exp open
5t6 Ohm CA 18 pass closed
5t6 Ohm CA 18 std closed
5t6 Ohm CA 18 std2 open
5t6 Ohm CA 18 exp open
...
I would like for the json objects to look like this:
{ "id": "3bf", "name": "JFK Int", "cats":
{ [ { "cat": "pass", "status": "open" },
{ "cat": "std", "status": "closed" },
{ "cat": "exp", "status": "open" } ] }
{ "id": "5t6", "name": "Ohm CA", "cats":
{ [ { "cat": "pass", "status": "closed" },
{ "cat": "std", "status": "closed" },
{ "cat": "std2", "status": "open" } ],
{ "cat": "exp", "status": "open" } ] }
I have succesfully connected to mysql and exported using json_encode using flat tables but this part I do not know how to do in PHP. Thanks.
This is the code that I have. This returns an array of json objects but it is flat, not nested:
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[] = $row;}
$json = json_encode($arr);
echo $json;
The data itself is from a view that combines the tables ports and cats.
what you could do (sorry, not the best code I could write... short on time, ideas, and energy ;-) is something like this (I hope it still conveys the point):
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
// You're going to overwrite these at each iteration, but who cares ;-)
$arr[$row['id']]['id'] = $row['id'];
$arr[$row['id']]['name'] = $row['name'];
// You add the new category
$temp = array('cat' => $row['cat'], 'status' => $row['status']);
// New cat is ADDED
$arr[$row['id']]['cats'][] = $temp;
}
$base_out = array();
// Kind of dirty, but doesn't hurt much with low number of records
foreach ($arr as $key => $record) {
// IDs were necessary before, to keep track of ports (by id),
// but they bother json now, so we do...
$base_out[] = $record;
}
$json = json_encode($base_out);
echo $json;
Haven't had the time to test or think twice about it, but again, I hope it conveys the idea...
With thanks to #maraspin, I have got my below code:
function merchantWithProducts($id)
{
if (
!empty($id)
) {
//select all query
$query = "SELECT
m.id as 'mMerchantID', m.name as 'merchantName', m.mobile, m.address, m.city, m.province,
p.id as 'ProductID', p.merchantId as 'pMerchantID', p.category, p.productName, p.description, p.price, p.image, p.ratingCount
FROM " . $this->table_name . " m
JOIN by_product p
ON m.id = p.merchantId
WHERE m.id = :id
GROUP BY m.id";
// prepare query statement
$stmt = $this->conn->prepare($query);
// sanitize
// $this->id = htmlspecialchars(strip_tags($this->id));
// bind values
$stmt->bindParam(":id", $this->id);
try {
$success = $stmt->execute();
if ($success === true) {
$results = $stmt->fetchAll();
$this->resultToEncode = array();
foreach ($results as $row) {
$objItemArray = array(
"merchantID" => $row->mMerchantID,
"merchantName" => $row->merchantName,
"mobile" => $row->mobile,
"address" => $row->address,
"city" => $row->city,
"province" => $row->province,
"product" => array(
"productID" => $row->ProductID,
"pMerchantID" => $row->pMerchantID,
"category" => $row->category,
"productName" => $row->productName,
"description" => $row->description,
"price" => $row->price,
"image" => $this->baseUrl . 'imagesProducts/' . $row->image,
"ratingCount" => $row->ratingCount
)
);
array_push($this->resultToEncode, $objItemArray);
}
http_response_code(200);
$httpStatusCode = '200 OK';
$pass = true;
// return json_encode($resultToEncode);
} else {
http_response_code(204);
$httpStatusCode = '204 No Content';
$pass = false;
$this->resultToEncode = 'No Record Found';
}
} catch (PDOException $pdoEx) {
http_response_code(500); // internal server error.
$httpStatusCode = '500 Internal Server Error';
$pass = false;
$this->resultToEncode = $pdoEx->getCode();
} catch (Exception $ex) {
// return $ex->getMessage();
http_response_code(404); // 404 Not Found.
$httpStatusCode = '404 Not Found';
$pass = false;
$this->resultToEncode = $ex->getMessage();
}
} else {
http_response_code(400);
$httpStatusCode = '400 bad request';
$pass = false;
$this->resultToEncode = 'User id not specified';
}
echo json_encode(array('passed' => $pass, 'Response' => $httpStatusCode, 'result' => $this->resultToEncode));
}

Categories