Facebook credit Integration errors - php

I have created a facebook application for integrating facebook credits.It is working fine but i have some doubts regarding on that
In call back payment get items function i have used this code for assigning order information
if ($func == 'payments_get_items') {
// remove escape characters
$order_info = stripcslashes($payload['order_info']);
if (is_string($order_info)) {
$item = json_decode($order_info, true);
$item['item_id'] = intval($item['GreeID']);
}
}
I want to get the item_id in 'payments_status_update update function.I have used $payload['order_details'] method .I am getting all the values in a json format.But when i use json_decode the purchase is not working properly.Is their any other method to get the item_id inside payments_status_update function
if ($func == 'payments_status_update')
{
$payload['order_details']
}

$order_info = json_decode(preg_replace('/:(\d+)/', ':"${1}"',stripcslashes($payload['order_details'])),true);

Related

How to invoke the demo url using VinceG php-first-data-api

I am trying to integrate First Data e4 Gateway using PHP. I downloaded the VinceG/php-first-data-api PHP First Data Service API class. The code comes with some examples.
I have my Terminal ID (API_LOGIN) and Password (32 character string).
What confuses me is that when I use one of the examples, I don't know how to tell the class that I want to use the demo url, not the production url.
The class comes with two constants:
const LIVE_API_URL = 'https://api.globalgatewaye4.firstdata.com/transaction/';
const TEST_API_URL = 'https://api.demo.globalgatewaye4.firstdata.com/transaction/';
In the First Data console, when I generated my password, it said to use the v12 api, /transaction/v12, so I changed the protected $apiVersion = 'v12';
All I want to do is write my first development transaction using First Data e4. I have yet to get any kind of response. Obviously I need a lot of hand holding to get started.
When I set up a website to use BalancedPayments, they have a support forum that's pretty good, and I was able to get that running fairly quickly. First Data has a lot of documentation, but for some reason not much of it has good PHP examples.
My hope is that some expert has already mastered the VinceG/php-first-data-api, and can help me write one script that works.
Here's the pre-auth code I'm using, that invokes the FirstData class:
// Pre Auth Transaction Type
define("API_LOGIN", "B123456-01");
define("API_KEY", "xxxxxxxxxxyyyyyyyyyyyyzzzzzzzzzz");
$data = array();
$data['type'] = "00";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vance";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33333";
$data['cvv'] = "123";
$data['address'] = "1111 OCEAN BLVD MIAMI FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
// Charge
$firstData->setTransactionType(FirstData::TRAN_PREAUTH);
$firstData->setCreditCardType($data['type'])
->setCreditCardNumber($data['number'])
->setCreditCardName($data['name'])
->setCreditCardExpiration($data['exp'])
->setAmount($data['amount'])
->setReferenceNumber($orderId);
if($data['zip']) {
$firstData->setCreditCardZipCode($data['zip']);
}
if($data['cvv']) {
$firstData->setCreditCardVerification($data['cvv']);
}
if($data['address']) {
$firstData->setCreditCardAddress($data['address']);
}
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
My number one problem was that I had not created (applied for, with instant approval) a
demo account on First Data. I didn't realize this was a separate thing on First Data. On Balanced Payments, for instance, you have one account, and you can run your script on a test url with test values.
From the Administration panel, click "Terminals", then your Gateway number on the ECOMM row (will look something like AH1234-03), then you have to click "Generate" on password save it to your personal notes), then click UPDATE.
Now replace your parameter values in your test scripts. I use a variable assignment block that looks something like this:
define("API_LOGIN", "AH1234-05"); //fake
define("API_KEY", "44p7797xxx790098z1z2n6f270ys1z0x"); //fake
$data = array();
$data['type'] = "03";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vancce";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33320";
$data['cvv'] = "123";
$data['address'] = "1234 N OCEAN BLVD MIAMI BEACH FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
at the end of the VinceG test scripts, I output my gateway response with a print_r, like this:
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
echo "<pre>";
print_r($firstData);

Facebook API Real Time update v2.2 read update

I was working in php
I did the work and sottoiscrizione
facebook api is v.2.2
but now there is a problem
how do I read the updates of the feeds I get ?
The code is :
<?php
//file of program
require_once('LoginFb.php');
require_once('FbClass.php');
require_once('dbClass.php');
require_once('FacebookClass.php');
//receive a Real Time Update
$method = $_SERVER['REQUEST_METHOD'];
// In PHP, dots and spaces in query parameter names are converted to
// underscores automatically. So we need to check "hub_mode" instead
// of "hub.mode".
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
$_GET['hub_verify_token'] == 'thisisaverifystring') {
echo $_GET['hub_challenge']; //print the code on the page that Facebook expects to read for confirmation
} else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
// Replace with your own code here to handle the update
// Note the request must complete within 15 seconds.
// Otherwise Facebook server will consider it a timeout and
// resend the push notification again.
$testo=json_decode($updates["entry"]);
$var=fopen("nome_file.txt","a+");
fwrite($var, "ciao");
fwrite($var, $updates );
fclose($var);
error_log('updates = ' . print_r($updates, true));
}
?>
In the above file "$update" contains an updated feed, but how to extract?
Note: subscription WORKS and updates arrived on my server.
Help me please :)
According to the Facebook documentation [link]:
Note that real-time updates only indicate that a particular field has changed, they do not include the value of those fields. They should be used only to indicate when a new Graph API request to that field needs to be made.
So, you don't get the updated data instead you get the updated feild name. On receiving an update, you should extract the changed field (I have explained this below) and make a new Graph API request to that field. Finally, you will get the updated field data.
How to extract the user name and changed field?
You receive this:
{"entry":[{"id":"****","uid":"****","time":1332940650,"changed_fields":{"status"]}],"object":"user"}
where "id" is my pageId and "changed_fields" is an array of changed fields.
You can extract these as following:
$entry = json_decode($updates["entry"]); <br>
$page = json_decode($entry["uid"]); <br>
$fields = json_decode($entry["changed_fields"]);
Hope it helps! :)
No function -> the respose contain a array of array the correct code is:
$json = json_decode($updates["entry"][0]["uid"], true);

GET Json API Results

I searched for this but most of the questions related to this are for API's with other services.
I'm building an API that allows game developers to send and retrieve user info from my database.
I was finally able to put together the API, but now I need to call the API.
1st when the game initiates, it sends us the game developers key their developer id and game id.
//Game loads, get developer key, send token and current high score
// == [ FIRST FILTER - FILTER GET REQUEST ] == //
$_GET = array_map('_INPUT', $_GET); // filter all input
// ====================================== //
// ============[ ACTION MENU ]=========== //
// ====================================== //
if(!empty($_GET['action']) && !empty($_GET['user']) && !empty($_GET['key']) && !empty($_GET['email']) && !empty($_GET['password'])): // if key data exists
switch($_GET['action']):
//athenticate game developer return and high score
case 'authenticate':
$db = new PDO('mysql:host=localhost;dbname=xxxx', 'xxxx', 'xxxx');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$st = $db->prepare("SELECT * FROM `game_developers_games` WHERE `id` = :gameid AND `developer_id`=:user AND `key`= :key AND `developer_active` = '1'"); // need to filter for next auction
$st->bindParam(':user', $_GET['user']); // filter
$st->bindParam(':key', $_GET['key']); // filter
$st->execute();
$r = $st->fetch(PDO::FETCH_ASSOC);
if($st->rowCount() == 0):
$return = array('DBA_id'=>'0000');
echo json_encode($return);
else:
$token = initToken($_GET['key'],$_GET['user']);
if($token == $r['API_Token']):
$return = array(
'DBA_id'=>$token,
'DBA_servertime'=>time(),
'DBA_highscore'=>$r['score'],
);
echo json_encode($return);
endif;
endif;
break;
Here's the script the game developer will have to add to their game to get the data when the game loads. Found this on another stackoverflow question but it's not working.
$.getJSON("https://www.gamerholic.com/gamerholic_api/db_api_v1.php? user=1&key=6054abe3517a4da6db255e7fa27f4ba001083311&gameid=1&action=authenticate", function () {
alert("aaa");
});
Try adding &callback=? to the end of the url you are constructing. This will enable jsonp that is accepted by cors.
$.getJSON("https://www.gamerholic.com/gamerholic_api/db_api_v1.php?user=1&key=6054abe3517a4da6db255e7fa27f4ba001083311&gameid=1&action=authenticate&callback=?", function () {
alert("aaa");
});
As per cross domain origin policy you cannot access cross domain url using jquery getJson function.
A callback is required to manage cross domain request using json and it needs to be handled on the server as well as the client end.
Also make sure to check the response using firebug or similar tool because as of now it is returning response code as 200.
I am mentioning two threads here which can guide you the right way
Jquery getJSON cross domain problems
http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/

Paypal Adaptive Payments works in sandbox mode but not production

I'm trying to use Paypal's adaptive payments API and having a tough time switching it to production. Everything works as expected on sandbox mode and I get a proper response, but when I switch to my live APP ID it doesn't work.
These are the configuration values I'm using for sandbox
PayPal URL : https://www.sandbox.paypal.com/webapps/adaptivepayment/flow/pay?paykey=[TOKEN_HERE]
Application ID : APP-80W284485P519543T
These values work for me in sandbox mode. But when I switch to the below production values, it stops working
PayPal URL : https://www.paypal.com/webapps/adaptivepayment/flow/pay?paykey=[TOKEN_HERE]
Application ID : [ACTUAL APP ID]
This is what I mean by stops working.
In production mode, the application gets the paykey
Appends it to the Paypal URL and then redirects it to their site
On site load, I get the following message
This transaction has already been approved. Please visit your PayPal Account Overview to see the details
The final URL it ends up on - https://ic.paypal.com/webapps/adaptivepayment/flow/payinit?execution=e6s1
Screenshot - http://screencast.com/t/28qJZ9CIk
There is also a 'Return' button there, and when I click on it I get taken to a different site each time (Looks like I get sent to random failUrls)
I've included the code I use below
$payRequest = new PayRequest();
$payRequest->actionType = "PAY";
$payRequest->cancelUrl = $cancelURL; //my success and fail urls
$payRequest->returnUrl = $returnURL;
$payRequest->clientDetails = new ClientDetailsType();
$payRequest->clientDetails->applicationId = $this->config['application_id'];
$payRequest->clientDetails->deviceId = $this->config['device_id'];
$payRequest->clientDetails->ipAddress = $this->CI->input->ip_address();
$payRequest->currencyCode = $currencyCode;
$payRequest->requestEnvelope = new RequestEnvelope();
$payRequest->requestEnvelope->errorLanguage = "en_US";
//I set the receiver and the amounts. I also define that these are digital goods payments
$receiver1 = new receiver();
$receiver1->email = $opts['receiver_email'];
$receiver1->amount = $opts['amount'];
$receiver1->paymentType = 'DIGITALGOODS';
$payRequest->receiverList = new ReceiverList();
$payRequest->receiverList = array($receiver1);
//Then I make the call
$ap = new AdaptivePayments();
$response = $ap->Pay($payRequest);
if(strtoupper($ap->isSuccess) == 'FAILURE') {
log_message('error', "PAYMENT_FAIL : " . print_r($ap->getLastError(), true));
return false;
} else {
if($response->paymentExecStatus == "COMPLETED") {
header("Location: " . $this->config['success_url']);
exit;
} else {
$token = $response->payKey;
$payPalURL = $this->config['paypal_redirect_url'] . 'paykey='.$token;
header("Location: ".$payPalURL);
exit;
}
}
This is code taken from their sample implementation, so not really sure what's going wrong here. Other information that might be relevant
I'm using adaptive payments to make sure that the sender and receiver
actually did the transaction
I have set the payment type as 'DIGITAL GOODS'
EDIT
I've included a sample URL with the pay key attached
https://www.paypal.com/webapps/adaptivepayment/flow/pay?paykey=AP-0H388650F08226841
I found the issue that was giving me all of this grief.
The Paypal SDK uses a couple of constants which are defined in /sdk/lib/Config/paypal_sdk_clientproperties
The constants contain the username, password, application_id the API url and a few others. These are used directly in the file /sdk/lib/CallerServices,php. So contrary to what you would expect in an API, these values are not injected in the setup phase so if you don't notice that file and change the values, the above code will not work.
To fix the issue, simply update the values defined in the file and you should be good to go.

facebook api: count attendees for event (limit problem)

Okay normally I'm all fine about the facebook API but I'm having a problem which just keeps me wondering. (I think it's a bug (Check ticket http://bugs.developers.facebook.net/show_bug.cgi?id=13694) but I wanted to throw it here if somebody has an idea).
I'm usng the facebook PHP library to count all attendees for a specific event
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending');
this works without a problem it correctly returns an array with all attendees...
now heres the problem:
This event has about 18.000 attendees right now.
The api call returns a max number of 992 attendees (and not 18000 as it should).
I tried
$attending = $facebook->api('/'.$fbparams['eventId'].'/attending?limit=20000');
for testing but it doesn't change anything.
So my actual question is:
If I can't get it to work by using the graph api what would be a good alternative? (Parsing the html of the event page maybe?) Right now I'm changing the value by hand every few hours which is tedious and unnecessary.
Actually there are two parameters, limit and offset. I think that you will have to play with both and continue making calls until one returns less than the max. limit.
Something like this, but in a recursive approach (I'm writting pseudo-code):
offset = 0;
maxLimit = 992;
totalAttendees = count(result)
if (totalAttendees >= maxLimit)
{
// do your stuff with each attendee
offset += totalAttendees;
// make a new call with the updated offset
// and check again
}
I've searched a lot and this is how I fixed it:
The requested URL should look something like this.
Here is where you can test it and here is the code I used:
function events_get_facebook_data($event_id) {
if (!$event_id) {
return false;
}
$token = klicango_friends_facebook_token();
if ($token) {
$parameters['access_token'] = $token;
$parameters['fields']= 'attending_count,invited_count';
$graph_url = url('https://graph.facebook.com/v2.2/' . $event_id , array('absolute' => TRUE, 'query' => $parameters));
$graph_result = drupal_http_request($graph_url, array(), 'GET');
if(is_object($graph_result) && !empty($graph_result->data)) {
$data = json_decode($graph_result->data);
$going = $data->attending_count;
$invited = $data->invited_count;
return array('going' => $going, 'invited' => $invited);
}
return false;
}
return false;
}
Try
SELECT eid , attending_count, unsure_count,all_members_count FROM event WHERE eid ="event"

Categories