I need to implement BeanStream payment gateway in my php code.I am new in payment gateway implementation. Can anybody help me with any demo project or scripts? prior thanks.
I know this is an old question, but since I just implemented the Beanstream payment gateway in my code I thought I would answer for the record anyway:
Once you have an account with Beanstream you will be able to access their API manuals which provide some good documentation on all of the request and response fields. You can use the curl library in PHP to connect to the Beanstream API this very easily. Here is a sample method for performing a simple payment based on their documentation ($global_ccauth is just an ORM object that contains my request information, which I store each time in my database, including the response string from Beanstream, but BE CAREFUL AND YOU PROBABLY WANT TO obfuscate the credit card number in the ORM model before it is saved to the database, like I do):
public static function do_payment($global_ccauth, $submitted_card_number) {
$payment_result = array(
'status' => FALSE,
'response' => array(),
);
// attempt to process the payment using CURL and a POST request to the Beanstream server as per Beanstream's example
$request = curl_init();
// Get curl to POST
curl_setopt($request, CURLOPT_POST, 1);
curl_setopt($request, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // return the results instead of echoing them
curl_setopt($request, CURLOPT_URL, BEANSTREAM_URL);
// These are the transaction parameters that we will POST
$auth_parameters = "requestType=BACKEND";
$auth_parameters .= "&merchant_id=" . BEANSTREAM_MERCHANT;
$auth_parameters .= "&username=" . BEANSTREAM_API_USER;
$auth_parameters .= "&password=" . BEANSTREAM_API_PASS;
$auth_parameters .= "&trnCardOwner=" . $global_ccauth->trnCardOwner;
$auth_parameters .= "&trnCardNumber=". $submitted_card_number;
$auth_parameters .= "&trnExpMonth=" . $global_ccauth->trnExpMonth;
$auth_parameters .= "&trnExpYear=" . $global_ccauth->trnExpYear;
//$auth_parameters .= "&trnCardCvd=";
$auth_parameters .= "&trnOrderNumber=" . $global_ccauth->trnOrderNumber ;
$auth_parameters .= "&trnAmount=" . $global_ccauth->trnAmount;
$auth_parameters .= "&ordName=" . $global_ccauth->ordName;
$auth_parameters .= "&ordEmailAddress=" . $global_ccauth->ordEmailAddress;
$auth_parameters .= "&ordPhoneNumber=" . $global_ccauth->ordPhoneNumber;
$auth_parameters .= "&ordAddress1=" . $global_ccauth->ordAddress1;
$auth_parameters .= "&ordAddress2=" . $global_ccauth->ordAddress2;
$auth_parameters .= "&ordCity=" . $global_ccauth->ordCity;
$auth_parameters .= "&ordProvince=" . $global_ccauth->ordProvince;
$auth_parameters .= "&ordPostalCode=" . $global_ccauth->ordPostalCode;
$auth_parameters .= "&ordCountry=" . $global_ccauth->ordCountry;
curl_setopt($request, CURLOPT_POSTFIELDS, $auth_parameters);
// Now POST the transaction. $txResult will contain Beanstream's response
$auth_result = curl_exec($request);
curl_close($request);
if ($auth_result !== FALSE) {
// save the raw results
$global_ccauth->response = $auth_result;
$global_ccauth->save();
// parse the results
parse_str($auth_result, $parsed_result);
$payment_result['response'] = $parsed_result;
if ( ! empty($parsed_result['trnApproved']) && $parsed_result['trnApproved'] == 1) {
// the request was approved
$payment_result['status'] = TRUE;
} else {
// the request was not approved
// do something smart
}
} else {
// curl POST request failed
// do something smart
}
return $payment_result;
}
I have also implemented their recurring payments for processing monthly payments automatically and it seems to be working well. You just have to adjust the parameters you send as per their API documentation.
PHP-Payments seems to be what you're looking for http://payments.calvinfroedge.com/
Related
Currently I have a system that sends multiple requests to a REST API. It is structured something like this:
foreach ($data as $d)
{
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_HTTPHEADER, (array of data here));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
$retry = 0;
while((curl_errno($ch) == 7 || curl_errno($ch) == 52) && $retry < 3)
{
$response = curl_exec($ch);
$retry++;
}
curl_close($ch);
(decode XML Response and loop)
}
(I can't expose the whole code so I have filled in the operations that are happening in brackes)
However after a few hundred requests the FastCGI script stalls. The REST API will still respond during this period if I query it in another fashion, but this batch client will not send anymore requests. After a few minutes, it will start responding again. I'm not sure why this is stalling, I can see via htop that there is no CPU activity on the threads at either end whilst this is happening.
Is there any reason why the cURL/PHP script would stall here?
if you allowed to use external PHP libraries;
I'd like to suggest this method:
https://github.com/php-curl-class/php-curl-class
// Requests in parallel with callback functions.
$multi_curl = new MultiCurl();
$multi_curl->success(function($instance) {
echo 'call to "' . $instance->url . '" was successful.' . "\n";
echo 'response: ' . $instance->response . "\n";
});
$multi_curl->error(function($instance) {
echo 'call to "' . $instance->url . '" was unsuccessful.' . "\n";
echo 'error code: ' . $instance->error_code . "\n";
echo 'error message: ' . $instance->error_message . "\n";
});
$multi_curl->complete(function($instance) {
echo 'call completed' . "\n";
});
$multi_curl->addGet('https://www.google.com/search', array(
'q' => 'hello world',
));
$multi_curl->addGet('https://duckduckgo.com/', array(
'q' => 'hello world',
));
$multi_curl->addGet('https://www.bing.com/search', array(
'q' => 'hello world',
));
$multi_curl->start();
Yesterday, I posted about Search for Mentions of a Topic with the Twitter API. I asked about what URL to use, since I thought I was doing it wrong.
As it turns out, my initial guess on which URL to use was correct (as it should have been, since I used Twitter Dev Console to get the URL. The problem seems to be in actually using the URL in the code I found. I have very limited understanding of the Twitter API, but it seems to be very difficult to do simple things now...
I'm trying to use this code (which I found in a blog post) to access tweets. When I load a PHP page with just this code (with my information in it, of course), I have no problem seeing tweets from my personal account (I DO have an application set up on my account, of course). But when I try to change the two URLs in the code itself, I get {"errors":[{"message":"Could not authenticate you","code":32}]}. So how else do I need to modify the code?
Note: HERE is the original blog post I found the code for.
EDIT: Here is the code I'm using exactly (well, minus my info):
<?php
//After you create the app at http://dev.twitter.com, you'll need to get the following four pieces of data from the details tab in your app's page.
$consumer_key = '';
$consumer_secret = '';
$access_token = '';
$access_token_secret = '';
$oauth_hash = 'oauth_consumer_key='.$consumer_key.
'&oauth_nonce='.time().
'&oauth_signature_method=HMAC-SHA1&oauth_timestamp='.
time().'&oauth_token='.$access_token.'&oauth_version=1.0';
// $base = 'GET&'.rawurlencode('http://api.twitter.com/1.1/search/tweets.json?q=apple&result_type=recent&count=10').
// '&'.rawurlencode($oauth_hash);
$base = 'GET&'.rawurlencode('https://api.twitter.com/1.1/statuses/user_timeline.json').
'&'.rawurlencode($oauth_hash);
$key = rawurlencode($consumer_secret).'&'. rawurlencode($access_token_secret);
$signature = base64_encode(hash_hmac('sha1', $base, $key, true));
$signature = rawurlencode($signature);
$oauth_header = 'oauth_consumer_key="'.$consumer_key.'",
oauth_nonce="' . time() . '",oauth_signature="' . $signature . '",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="' . time() . '",
oauth_token='.$access_token.',
oauth_version="1.0", ';
$curl_header = array("Authorization: Oauth {$oauth_header}", 'Expect:');
$curl_request = curl_init();
curl_setopt($curl_request, CURLOPT_HTTPHEADER, $curl_header);
curl_setopt($curl_request, CURLOPT_HEADER, false);
// curl_setopt($curl_request, CURLOPT_URL, 'http://api.twitter.com/1.1/search/tweets.json?q=apple&result_type=recent&count=10');
curl_setopt($curl_request, CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json');
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, false);
$json = curl_exec($curl_request);
curl_close($curl_request);
echo $json;
Personally I would try one of Twitter's recommended PHP libraries (this one looks lightweight and good: https://github.com/J7mbo/twitter-api-php).
In other news, there was a follow up post to the one you are working with that corrected this issue: http://blog.jacobemerick.com/web-development/passing-extra-parameters-to-twitter-via-oauth/
Hash Change:
$oauth_hash = '';
$oauth_hash .= 'count=TOTAL_COUNT_YOU_WANT&';
$oauth_hash .= 'oauth_consumer_key=YOUR_CONSUMER_KEY&';
$oauth_hash .= 'oauth_nonce=' . time() . '&';
$oauth_hash .= 'oauth_signature_method=HMAC-SHA1&';
$oauth_hash .= 'oauth_timestamp=' . time() . '&';
$oauth_hash .= 'oauth_token=YOUR_ACCESS_TOKEN&';
$oauth_hash .= 'oauth_version=1.0&';
$oauth_hash .= 'screen_name=SCREEN_NAME_HERE';
Header Change:
$oauth_header = '';
$oauth_header .= 'count="TOTAL_COUNT_YOU_WANT", ';
$oauth_header .= 'oauth_consumer_key="YOUR_CONSUMER_KEY", ';
$oauth_header .= 'oauth_nonce="' . time() . '", ';
$oauth_header .= 'oauth_signature="' . $signature . '", ';
$oauth_header .= 'oauth_signature_method="HMAC-SHA1", ';
$oauth_header .= 'oauth_timestamp="' . time() . '", ';
$oauth_header .= 'oauth_token="YOUR_ACCESS_TOKEN", ';
$oauth_header .= 'oauth_version="1.0", ';
$oauth_header .= 'screen_name="SCREEN_NAME_HERE"';
curl change:
curl_setopt($curl_request, CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json?count=TOTAL_COUNT_YOU_WANT&screen_name=SCREEN_NAME_HERE');
I'm trying to figure out how to get this working with PHP. I have a working IPN for paypal that is less than 20 lines of code to get the data I need. I have tried reading the Google docs but they are either way too specific or way too general. There is some sample code, which is about 1300 lines in 5 files and I can't make sense of it. I just need a handful of vars back from a completed transaction, nothing more. Is it possible to do this with a few lines of code (and I mean without 1300 lines worth of "include" files) or is Google Checkout's process really that bulky?
Here's a bit of code I started. Not yet finished.
It works perfectly.
All you need to do is take the data Google sends back and this code writes to a file and use it to insert into your sales table send notification of payment received to customer and so on.
The trick is that when Google sends you a post you must call back with and Authorization header or it will not take it in consideration.
function post2google($url, $timeout = 30, $port = 80, $buffer = 128) {
$mid = "123456789";
$mky = "qwertyuiop";
$aut = base64_encode($mid . ":" . $mky);
$arr = parse_url($url);
$ssl = "";
if($arr['scheme'] == "https") $ssl = "ssl://";
$post = "POST " . $arr['path'] . " HTTP/1.1\r\n";
$post .= "Host: " . $arr['host'] . "\r\n";
$post .= "Authorization: Basic " . $aut . "\r\n";
$post .= "Content-Type: application/xml; charset=UTF-8\r\n";
$post .= "Accept: application/xml; charset=UTF-8\r\n";
$post .= "Content-Length: " . strlen($arr['query']) . "\r\n";
$post .= "Connection: Close\r\n";
$post .= "\r\n";
$post .= $arr['query'];
$f = fsockopen($ssl . $arr['host'], $port, $errno, $errstr, $timeout);
if(!$f)
return $errstr . " (" . $errno . ")";
else{
fputs($f, $post);
while(!feof($f)) { $echo .= #fgets($f, $buffer); }
fclose($f);
return $echo;
}
}
$re = post2google("https://checkout.google.com/api/checkout/v2/reportsForm/Merchant/123456789?_type=notification-history-request&serial-number=" . $_REQUEST['serial-number'], 3, 443);
$re = str_replace("&", "\n", $re) . "\n\n--\n\n";
file_put_contents("gpn.txt", $re, FILE_APPEND);
I've gotten it to work, and here's the skeleton of my code that can be used to handle HTTP notifications/responses. This was obviously derived from tntu's example above. (Thanks!)
//incoming data is in the var $_POST['serial-number']
//"send" the response to acknowledge the serial number that google talks about all over but never explains how
echo "_type=notification-acknowledgment&serial-number=".$_POST['serial-number'];
//now we need to call google's server and ask for this transaction's data:
//you'll need to change your merchant id in the $url and $mid vars, and your merchant key in the $mky var
$url = "https://sandbox.google.com/checkout/api/checkout/v2/reportsForm/Merchant/1234567890?_type=notification-history-request&serial-number=" . $_REQUEST['serial-number'];
$mid = "1234567890";
$mky = "ABCDEFGHIJK";
$aut = base64_encode($mid . ":" . $mky);
$arr = parse_url($url);
$ssl = "";
if($arr['scheme'] == "https") $ssl = "ssl://";
$post = "POST " . $arr['path'] . " HTTP/1.1\r\n";
$post .= "Host: " . $arr['host'] . "\r\n";
$post .= "Authorization: Basic " . $aut . "\r\n";
$post .= "Content-Type: application/xml; charset=UTF-8\r\n";
$post .= "Accept: application/xml; charset=UTF-8\r\n";
$post .= "Content-Length: " . strlen($arr['query']) . "\r\n";
$post .= "Connection: Close\r\n";
$post .= "\r\n";
$post .= $arr['query'];
//now we actually make the request by opening a socket and calling Google's server
$f = fsockopen($ssl . $arr['host'], 443, $errno, $errstr, 30);
if(!$f){
//something failed in the opening of the socket, we didn't contact google at all, you can do whatever you want here such as emailing yourself about it and what you were trying to send, etc
#mail("troubleshooting#yourdomain.com","Google IPN - HTTP ERROR ",$errstr . " (" . $errno . ")\n\n\n".$arr['query']);
}else{
//the socket was opened, send the request for the order data:
fputs($f, $post); // you're sending
while(!feof($f)) { $response .= #fgets($f, 128); } //google replies and you store it in $response
fclose($f); //close the socket, we're done talking to google's server
$spl=strpos($response,"_type="); //parse the type because parse_str won't catch it
if ($spl!==false){
$spl2=strpos($response,"&",$spl);
$ordertype=substr($response,($spl+6),($spl2-$spl)-6);
}//$ordertype will tell you which type of notification is being sent, new-order-notification, risk-information-notification, etc
$subresponse=substr($response,$spl2+1); //put the rest of it into an array for easy access
parse_str($subresponse,$order);//you can now access google's response in $order[] vars
//IMPORTANT: dots in Google's field names are replaced by underscore, for example:
// $order['google-order-number'] and $order['buyer-billing-address_address1'] NOT $order['buyer-billing-address.address1']
//order field names are shown here:
//https://developers.google.com/checkout/developer/Google_Checkout_HTML_API_Notification_API#order_summary
//this is the point where you will want to use the data contained in $order[] to create a new record in your database or whatever.
//NOTE: be sure to store and check for duplicates using the google-order-number because you will get multiple notifications from google regarding the same order
if (strtoupper($order['order-summary_financial-order-state']) == "CHARGEABLE"){
//CHARGEABLE is what indicates it is safe to create a login for the user (if you are delivering digital goods)
// insert into db, and/or email user with key or download url
}
}
I have spent the past couple of hours trying all types of variations but according to the Twitter API this should have worked from step 1!
1 addition I have made to the script below is that I have added in:
$header = array("Expect:");
This I found helped in another question on stackoverflow from getting a denied issue / 100-continue.
Issue:
Failed to validate oauth signature and token is the response EVERY time!!!
Example of my post data:
Array ( [oauth_callback] => http://www.mysite.com//index.php [oauth_consumer_key] => hidden [oauth_nonce] => hidden [oauth_signature_method] => HMAC-SHA1 [oauth_timestamp] => 1301270847 [oauth_version] => 1.0 )
And my header data:
Array ( [0] => Expect: )
Script:
$consumer_key = "hidden";
$consumer_secret = "hidden";
function Post_Data($url,$data,$header){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$data['oauth_callback'] = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$data['oauth_consumer_key'] = $consumer_key;
$data['oauth_nonce'] = md5(time());
$data['oauth_signature_method'] = "HMAC-SHA1";
$data['oauth_timestamp'] = time();
$data['oauth_version'] = "1.0";
$header = array("Expect:");
$content = Post_Data("http://api.twitter.com/oauth/request_token",$data,$header);
print_r($content);
Can anybody see an obvious mistake that I may be making here? Preferably I would not like to go with somebody elses code as most examples have full classes & massive functions, I am looking for the most simple approach!
Your problem is that you did not include the OAuth signature in your request.
You can read about the concept on this page.
A working implementation can be found here.
I faced same issue, what I was missing is passing header in to the curl request.
As shown in this question, I was also sending the $header = array('Expect:'), which was the problem in my case. I started sending signature in header with other data as below and it solved the case for me.
$header = calculateHeader($parameters, 'https://api.twitter.com/oauth/request_token');
function calculateHeader(array $parameters, $url)
{
// redefine
$url = (string) $url;
// divide into parts
$parts = parse_url($url);
// init var
$chunks = array();
// process queries
foreach($parameters as $key => $value) $chunks[] = str_replace('%25', '%', urlencode_rfc3986($key) . '="' . urlencode_rfc3986($value) . '"');
// build return
$return = 'Authorization: OAuth realm="' . $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '", ';
$return .= implode(',', $chunks);
// prepend name and OAuth part
return $return;
}
function urlencode_rfc3986($value)
{
if(is_array($value)) return array_map('urlencode_rfc3986', $value);
else
{
$search = array('+', ' ', '%7E', '%');
$replace = array('%20', '%20', '~', '%25');
return str_replace($search, $replace, urlencode($value));
}
}
How to use twitter api with "http basic auth"?
I think I should use the "consumer key"! because twitter gave you limit rate of requests per hour, how can they count my requests if I didn't use my consumer key?
Whenever you want to use HTTP basic auth with anything, if you want to ignore the actual implementation and HTTP headers, just use cURL. Here's a simple example in PHP, cURL is available in other languages too:
<?php
$ch = curl_init();
// Sets the URL cURL will open
curl_setopt($ch, CURLOPT_URL, 'http://twitter.com/statuses/user_timeline.xml?screen_name=al3x');
// Here's the HTTP auth
// The 3rd argument is your Twitter username and password joined with a colon
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
// Makes curl_exec() return server response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Lately the Twitter API expects an Expect header. It's a mystery
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
// And here's the result XML
$twitter_xml = curl_exec($ch);
curl_close($ch);
?>
And then $twitter_xml will contain the XML of al3x's public timeline. As far as rate limiting goes, ceejayoz already answered that pretty well.
Authenticated API GET requests are counted against your user account's tally.
Unauthenticated API GET requests (permitted by some methods) are counted against your IP address's tally.
POST requests are not rate limited.
More details are available in the Twitter docs.
I would think that they count the requests from the same IP - but I haven't double checked.
Even dynamic IP address will be static for a session and, in the absence of any other identifying information, the only thing that will distinguish you from other users.
As other posters have said - there are better methods if you've got a key.
$twitter = file_get_content("http://user:password#twitter.com/blabla");
more about native HTTP Wrapper support in PHP
I recently wrote some PHP to post to Twitter
This is the working part of it:
$message = 'A new revision (#' . $data['revision'] . ') was commited by ' . $data['author'] . ': ' . $data['message'] . "";
$message = substr($message, 0, 140);
$content = 'status=' . urlencode($message);
$packetString = "POST /statuses/update.xml HTTP/1.1\r\n";
$packetString .= "Authorization: Basic " . base64_encode($username . ":" . $password) . "\r\n";
$packetString .= "Content-Length:" . strlen($content) . "\r\n";
$packetString .= "HOST: twitter.com\r\n";
$packetString .= "\r\n" . $content . "\r\n";
$sock = fsockopen('twitter.com', 80);
fwrite($sock, $packetString);
//This is some logging, to a local file so I can monitor local what's going on
$response = fread($sock, 10240);
fwrite($fh, $packetString . "\r\n\r\n\r\n" . trim($response) . "\r\n\r\n\r\nD:\r\n" . $d);
fclose($fh);
You can see it in action here: http://twitter.com/fmsvn using a callback from our SVN server I am posting the SVN messages to the projects Twitter Feed.