Every time I run the code below, I get a WSOD. Not sure what I'm doing wrong with this code. Nothing gets logged and I've verified my php.ini configurations are well set to display all errors. Any help on this would be appreciated.
// MAIN BIDDING FUNCTION MAIN BIDDING FUNCTION
// this function performs no checking on the input variables
$username = '1*****';
$password = '******';
$item = '*******';
$bid = '***.**';
// $link - itemlink with referral, can leave empty i.e. ''
function place_bid($username, $password, $item, $bid, $link) {
$cookies = dirname(__FILE__).'/cookies.txt';
//set success as default false
$success = false;
$bid_success = false;
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_REFERER, $link);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookies);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookies);
//query the sign-out page
//curl_setopt($curl, CURLOPT_URL, "https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&lgout=1");
//$ret = curl_exec ($curl);
//query the referal link page
if ($link) {
curl_setopt($curl, CURLOPT_URL, $link);
$ret = curl_exec ($curl);
}
//IMPORTANT
//query the sign-in page to set the cookies
curl_setopt($curl, CURLOPT_URL, 'https://signin.ebay.com/aw-cgi/eBayISAPI.dll?SignIn&campid=5337161990&customid=7');
$ret = curl_exec ($curl);
$data = [];
$numbers = [];
if (preg_match('%(<form name="SignInForm".*?<\/form)%im', $ret, $regs)) {
$dom = new DOMDocument;
$dom-loadHTML($regs[0]);
$nodes = $dom-getElementsByTagName('input');
foreach($nodes as $node) {
$name = $node-getAttribute('name');
$value = $node-getAttribute('value');
//$size = $node-getAttribute('size');
$type = $node-getAttribute('type');
$data[$name] = $value;
if (is_numeric($name)) {
if ($type == 'text') {
$data[$name] = $username;
}
if ($type == 'password') {
$data[$name] = $password;
}
}
}
}
unset($data['']);
$data_str = http_build_query($data);
//sign-in
curl_setopt($curl, CURLOPT_URL, "https://signin.ebay.com/ws/eBayISAPI.dll?co_partnerId=2&siteid=0&UsingSSL=1");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_str);
$ret = curl_exec ($curl);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
if (!$ret) {
$ret = curl_exec ($curl);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
if (!$ret) {
$ret = curl_exec ($curl);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
}
}
curl_setopt($curl, CURLOPT_URL, 'https://www.ebay.com/myb/WatchList');
$ret = curl_exec ($curl);
//test_write($ret);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
if (!$ret) {
$ret = curl_exec ($curl);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
if (!$ret) {
$ret = curl_exec ($curl);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
}
}
//if (strpos($ret, '"loggedIn":true') === FALSE) {
if ((strpos($ret, "userid={$username}") === FALSE) && (strpos($ret, "usr/{$username}") === FALSE)) {
if (preg_match('%<b class="altTitle"(.*)</b%', $ret, $regs)) {
$err = $regs[1];
ebaylog("\"{$err}\"");
if (strpos($err, 'The alerts below') === 0) {
ebaylog("{$item}: 'The alerts below' found, successful");
//set it to succes
}
} else {
ebaylog("{$item}: Failed signing in");
if (preg_match('%<font face=".*?" size="3"<b(.*?)</b</font%', $ret, $regs)) {
$err = $regs[1];
ebaylog("\"{$err}\"");
}
//test_write($ret);
goto end;
}
} else {
ebaylog("{$item}: Success signing in");
}
//place the inital bid
curl_setopt($curl, CURLOPT_URL, "https://offer.ebay.com/ws/eBayISAPI.dll?MakeBid&item={$item}&maxbid={$bid}&campid=5337161990&customid=7");
$ret = curl_exec ($curl);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
if (!$ret) {
$ret = curl_exec ($curl);
}
if (preg_match_all('/(?:value="([-0-9a-zA-Z]*)" *)?name="stok"(?: *value="([-0-9a-zA-Z]*)")?/', $ret, $regs)) {
$stok = $regs[1][0];
} else {
//Failed to get 'stok' value
//try and determine why
if (preg_match('%<div class="statusDiv"(.*?)</div%', $ret, $regs)) {
$err = $regs[1];
ebaylog("'{$err}'");
//if string starts with "Enter US $0.41 or more"
if (stripos($err, 'Enter') === 0) {
ebaylog("{$item}: 'Enter' found, aborting");
//set it to success
$success = true;
} else if (stripos($err, 'To enter a') === 0) {
ebaylog("{$item}: 'To enter a' found, aborting");
//set it to success
$success = true;
} else if (stripos($err, 'Transaction Blocked') === 0) {
ebaylog("{$item}: 'Transaction Blocked' found, aborting");
//set it to success
$success = true;
}
} else if (preg_match('%"\d*" - Invalid Item</div%', $subject)) {
ebaylog("{$item}: 'Invalid Item' found, aborting");
test_write($ret);
//set it to success
$success = true;
} else if (preg_match('%<div class="subTlt"<ul class="errList"<li(.*?)</li</ul</div%', $subject)) {
ebaylog("{$item}: 'no longer available' found, aborting");
test_write($ret);
//set it to success
$success = true;
} else if (preg_match('%id="w\d-\d-_msg".*?(.*?)</span%', $ret, $regs)) {
ebaylog("'{$regs[1]}'");
} else if (preg_match('%<div\s+class\s*=\s*"(?:errRed|errBlk|errTitle|statusDiv)"\s*(.*?)</div%i', $ret, $regs)) {
ebaylog("'{$regs[1]}'");
} else {
//don't know why so log the page
ebaylog("{$item}: Failed to get 'stok' value");
test_write($ret);
}
goto end;
}
if (preg_match_all('/(?:value="([-0-9a-zA-Z]*)" *)?name="uiid"(?: *value="([-0-9a-zA-Z]*)")?/', $ret, $regs)) {
$uiid = $regs[1][0];
} else {
ebaylog("{$item}: Failed to get 'uiid' value");
goto end;
}
if ($stok && $uiid) {
ebaylog("{$item}: Success placing initial bid");
} else {
ebaylog("{$item}: Failed placing initial bid");
goto end;
}
//confirm the bid
curl_setopt($curl, CURLOPT_URL, "https://offer.ebay.com/ws/eBayISAPI.dll?MfcISAPICommand=MakeBid&maxbid={$bid}&quant=1&mode=1&stok={$stok}&uiid={$uiid}&co_partnerid=2&user={$username}&fb=0&item={$item}&campid=5337161990&customid=7");
$ret = curl_exec ($curl);
if(curl_errno($curl)){
ebaylog('Curl error: ' . curl_error($curl));
}
if (!$ret) {
$ret = curl_exec ($curl);
}
//perform a number of tests to determine if the bid was a success
$bid_success = true;
if (stripos($ret, "you're the first bidder") === FALSE) {
if (stripos($ret, "you're the high bidder and currently in the lead") === FALSE) {
if (stripos($ret, "you're currently the highest bidder") === FALSE) {
$bid_success = false;
ebaylog("{$item}: Failed placing final bid");
//try and determine why
if (preg_match('%<div\s+class\s*=\s* (?:errRed|errBlk|errTitle|statusDiv|title)"\s*(.*?)</div%i', $ret, $regs)) {
$err = $regs[1];
ebaylog("'{$err}'");
if (stripos($err, 'Enter') === 0) {
ebaylog("{$item}: 'Enter' found, aborting");
//set it to success
$bid_success = true;
} else if (stripos($err, "You've just been outbid") === 0) {
ebaylog("{$item}: 'You've just been outbid' found, aborting");
//set it to success
$bid_success = true;
} else if (stripos($err, "You're currently the high bidder,") === 0) {
ebaylog("{$item}: 'You're currently the high bidder, but the reserve hasn't been met.' found, aborting");
//set it to success
$bid_success = true;
}
} else {
//we don't know why it failed so write the data
test_write($ret);
}
}
}
}
if ($bid_success) {
ebaylog("{$item}: Success placing final bid");
$success = true;
}
end:
//close the curl session
curl_close ($curl);
if ($success) {
ebaylog("{$item}: Success: {$username}");
} else {
ebaylog("{$item}: Failure: {$username}");
}
return $success;
}
?
Related
I have the following code which basically runs a bunch of curl request in a for loop
This is a background system job.. however when this code is running.. i can't access the website, website is just loading until this task/function is finished
public function endcount() {
$order_list = $this->order_model->get_rows([
'where' => [
"status IN ('Processing', 'In Progress') AND service_id = 1"
],
'order_by' => 'quantity ASC',
'limit' => '200'
]);
foreach ($order_list as $key => $value) {
$start_count = $value['start_count'];
//service id = 1 is for followers
if ($value['service_id'] == '1' || $value['service_id'] == '3' || $value['service_id'] == '5') {
$end_count = 0;
try {
$username = $value['target'];
$proxy = '139.99.54.49:10163';
$proxyauth = 'username:password';
$url = 'https://www.instagram.com/'. $username .'/?__a=1&__d=dis';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy); // PROXY details with port
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth); // Use if proxy have username and password
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json') );
$data = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
var_dump($error_msg);
}
$json_data = json_decode($data, true);
if ($json_data && array_key_exists('graphql', $json_data)) {
$end_count = $json_data['graphql']['user']['edge_followed_by']['count'];
} else {
var_dump($username . ' data ga bisa');
$end_count = 0;
}
curl_close($ch);
} catch(Exception $e) {
var_dump($e->getMessage());
$end_count = 0;
}
if ($end_count == -666) {
$end_count = $start_count + 5;
}
$total_followers = $start_count + $value['quantity'];
$remains = $total_followers - $end_count;
if ($remains <= 10) {
$status = 'Success';
} else {
$status = 'Partial';
}
var_dump('end count of ' . $value['target'] . ' ' . $end_count . ' WITH REMAINS: ' . $remains);
if ($status == 'Success') {
$update_order = [
'remains' => $remains,
'status' => $status,
'updated_at' => date('Y-m-d H:i:s'),
];
$update_order = $this->order_model->update($update_order, ['id' => $value['id']]);
if ($update_order == true) {
print('ID '.$value['id'].' => ['.$status.'] - [FINAL COUNT : '.$end_count.'] - [REMAINS : '.$remains.'] - [TARGET COUNT : '.$total_followers.']<br>');
} else {
print('Error..');
}
}
//var_dump($value['target']);
} else if ($value['service_id'] == '2') {
//service id = 2 is for likers
}
}
}
is there any way i can optimize this code so it is not blocking access to the site while running ?
try adding sleep(5); funtion to your code so server isn't overloaded with requests..
your code should look something like this :
foreach ($order_list as $key => $value) {
sleep(5);
$start_count = $value['start_count'];
I know this question has been asked multiple times, however looking through all the solutions, none of them have seemed to work for me.
I've been using the IPN Simulator on the PayPal website to integrate Subscriptions into my website, yet the IPN is always returning invalid.
I've tried multiple ways to get this working, but this is my current method:
<?php
class IpnListener {
public $use_curl = true;
public $force_ssl_v3 = false;
public $follow_location = false;
public $use_ssl = true;
public $use_sandbox = false;
public $timeout = 30;
private $post_data = array();
private $post_uri = '';
private $response_status = '';
private $response = '';
const PAYPAL_HOST = 'www.paypal.com';
const SANDBOX_HOST = 'www.sandbox.paypal.com';
protected function curlPost($encoded_data) {
if ($this->use_ssl) {
$uri = 'https://'.$this->getPaypalHost().'/cgi-bin/webscr';
$this->post_uri = $uri;
} else {
$uri = 'http://'.$this->getPaypalHost().'/cgi-bin/webscr';
$this->post_uri = $uri;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $this->follow_location);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
if ($this->force_ssl_v3) {
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
} else {
curl_setopt($ch, CURLOPT_SSLVERSION, 4);
}
$this->response = curl_exec($ch);
$this->response_status = strval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
if ($this->response === false || $this->response_status == '0') {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
}
protected function fsockPost($encoded_data) {
if ($this->use_ssl) {
$uri = 'ssl://'.$this->getPaypalHost();
$port = '443';
$this->post_uri = $uri.'/cgi-bin/webscr';
} else {
$uri = $this->getPaypalHost(); // no "http://" in call to fsockopen()
$port = '80';
$this->post_uri = 'http://'.$uri.'/cgi-bin/webscr';
}
$fp = fsockopen($uri, $port, $errno, $errstr, $this->timeout);
if (!$fp) {
// fsockopen error
throw new Exception("fsockopen error: [$errno] $errstr");
}
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Host: ".$this->getPaypalHost()."\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: ".strlen($encoded_data)."\r\n";
$header .= "Connection: Close\r\n\r\n";
fputs($fp, $header.$encoded_data."\r\n\r\n");
while(!feof($fp)) {
if (empty($this->response)) {
// extract HTTP status from first line
$this->response .= $status = fgets($fp, 1024);
$this->response_status = trim(substr($status, 9, 4));
} else {
$this->response .= fgets($fp, 1024);
}
}
fclose($fp);
}
private function getPaypalHost() {
if ($this->use_sandbox) return self::SANDBOX_HOST;
else return self::PAYPAL_HOST;
}
public function getPostUri() {
return $this->post_uri;
}
public function getResponse() {
return $this->response;
}
public function getResponseStatus() {
return $this->response_status;
}
public function getTextReport() {
$r = '';
// date and POST url
for ($i=0; $i<80; $i++) { $r .= '-'; }
$r .= "\n[".date('m/d/Y g:i A').'] - '.$this->getPostUri();
if ($this->use_curl) $r .= " (curl)\n";
else $r .= " (fsockopen)\n";
// HTTP Response
for ($i=0; $i<80; $i++) { $r .= '-'; }
$r .= "\n{$this->getResponse()}\n";
// POST vars
for ($i=0; $i<80; $i++) { $r .= '-'; }
$r .= "\n";
foreach ($this->post_data as $key => $value) {
$r .= str_pad($key, 25)."$value\n";
}
$r .= "\n\n";
return $r;
}
public function processIpn($post_data=null) {
$encoded_data = 'cmd=_notify-validate';
if ($post_data === null) {
// use raw POST data
if (!empty($_POST)) {
$this->post_data = $_POST;
$encoded_data .= '&'.file_get_contents('php://input');
} else {
throw new Exception("No POST data found.");
}
} else {
// use provided data array
$this->post_data = $post_data;
foreach ($this->post_data as $key => $value) {
$encoded_data .= "&$key=".urlencode($value);
}
}
if ($this->use_curl) $this->curlPost($encoded_data);
else $this->fsockPost($encoded_data);
if (strpos($this->response_status, '200') === false) {
throw new Exception("Invalid response status: ".$this->response_status);
}
if (strpos($this->response, "VERIFIED") !== false) {
return true;
} elseif (strpos($this->response, "INVALID") !== false) {
return false;
} else {
throw new Exception("Unexpected response from PayPal.");
}
}
public function requirePostMethod() {
// require POST requests
if ($_SERVER['REQUEST_METHOD'] && $_SERVER['REQUEST_METHOD'] != 'POST') {
header('Allow: POST', true, 405);
throw new Exception("Invalid HTTP request method.");
}
}
Then the Payment.php class, which is where PayPal sends the request too.
/*The Database Connection Code Is Here*/
include('ipnlistener.php');
$listener = new IpnListener();
$listener->use_sandbox = true;
//$listener->use_curl = false;
try {
$verified = $listener->processIpn();
} catch (Exception $e) {
file_put_contents("paymentdev.php", $e->getMessage()." ".date("H:i"));
//file_put_contents("paymentdev.php", "fudge");
exit(0);
}
if ($verified) {
file_put_contents("paymentdev.php", "test");
$data = $_POST;
$user_id = json_decode($data['custom'])->user_id;
$subscription = ($data['mc_gross_1'] == '49.95') ? 2 : 1;
$txn_id = $data['txn_id'];
$user_id = $user_id;
$paypal_id = $data['subsc_id'];
$subscription = $subscription;
$expires = date('Y-m-d H:i:s', strtotime('+1 Month'));
$sql = "SELECT * FROM payments WHERE user_id=$user_id";
$payment = $mysqli->query($sql);
if(isset($payment) && $payment->num_rows > 0)
{
$sql = "DELETE FROM payments WHERE user_id=$user_id";
$delete = $mysqli->query($sql);
}
$sql = "INSERT INTO payments (txn_id, user_id, paypal_id, expires, subscription) VALUES ('$txn_id', $user_id, '$paypal_id', '$expires', $subscription)";
$insertpayment = $mysqli->query($sql);
file_put_contents("paymentdev.php", $mysqli->error);
} else {
file_put_contents("paymentdev.php", "Transaction not verified ".date("H:i")."<br>".$listener->getTextReport());
echo "Error: Transaction not verified";
}
Thanks in advance for all your help guys!
Turns out the code I was using was just fine, I updated the server a bit more just to ensure it was using the latest cURL and open ssl, but even so the sandbox would always return INVALID. I tried the live version with subscriptions priced at $0.01 and the payment went through, was valid and my database was updated
Must just be something weird with the IPN simulator/sandbox
We are integrating Bitpay to our website but each time we make payment and call back out notification url we keep getting "no post data". Our url is https as requested and everything seem to be fine please help. this is the code.
bp_options.php
global $bpOptions;
$bpOptions['apiKey'] = 'xxxxxxx';
$bpOptions['verifyPos'] = true;
$bpOptions['notificationEmail'] = 'our email';
$bpOptions['notificationURL'] = 'https://www.ourwebsite.com/completesubscription/bitpaynotification';;
$bpOptions['redirectURL'] = 'https://www.ourwebsite.com/completesubscription?method=bitpay';;
$bpOptions['currency'] = 'USD';
$bpOptions['physical'] = true;
$bpOptions['fullNotifications'] = true;
$bpOptions['transactionSpeed'] = 'high';
$bpOptions['logFile'] = '/bplog.txt';
$bpOptions['useLogging'] = TRUE;
bp_lib.php
require_once 'bp_options.php';
function bpLog($contents) {
global $bpOptions;
try {
if(isset($bpOptions['logFile']) && $bpOptions['logFile'] != '') {
$file = dirname(__FILE__).$bpOptions['logFile'];
} else {
// Fallback to using a default logfile name in case the variable is
// missing or not set.
$file = dirname(__FILE__).'/bplog.txt';
}
file_put_contents($file, date('m-d H:i:s').": ", FILE_APPEND);
if (is_array($contents))
$contents = var_export($contents, true);
else if (is_object($contents))
$contents = json_encode($contents);
file_put_contents($file, $contents."\n", FILE_APPEND);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
function bpCurl($url, $apiKey, $post = false) {
global $bpOptions;
if((isset($url) && trim($url) != '') && (isset($apiKey) && trim($apiKey) != '')) {
try {
$curl = curl_init();
$length = 0;
if ($post) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
$length = strlen($post);
}
$uname = base64_encode($apiKey);
if($uname) {
$header = array(
'Content-Type: application/json',
'Content-Length: ' . $length,
'Authorization: Basic ' . $uname,
'X-BitPay-Plugin-Info: phplib1.5',
);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_PORT, 443);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // verify certificate
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // check existence of CN and verify that it matches hostname
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
$responseString = curl_exec($curl);
if($responseString == false) {
$response = array('error' => curl_error($curl));
if($bpOptions['useLogging'])
bpLog('Error: ' . curl_error($curl));
} else {
$response = json_decode($responseString, true);
if (!$response) {
$response = array('error' => 'invalid json: '.$responseString);
if($bpOptions['useLogging'])
bpLog('Error - Invalid JSON: ' . $responseString);
}
}
curl_close($curl);
return $response;
} else {
curl_close($curl);
if($bpOptions['useLogging'])
bpLog('Invalid data found in apiKey value passed to bpCurl. (Failed: base64_encode(apikey))');
return array('error' => 'Invalid data found in apiKey value passed to bpCurl. (Failed: base64_encode(apikey))');
}
} catch (Exception $e) {
#curl_close($curl);
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return array('error' => $e->getMessage());
}
} else {
// Invalid parameter specified
if($bpOptions['useLogging'])
bpLog('Error: You must supply non-empty url and apiKey parameters.');
return array('error' => 'You must supply non-empty url and apiKey parameters.');
}
}
function bpCreateInvoice($orderId, $price, $posData, $options = array()) {
global $bpOptions;
try {
$options = array_merge($bpOptions, $options); // $options override any options found in bp_options.php
$pos = array('posData' => $posData);
if ($bpOptions['verifyPos'])
$pos['hash'] = bpHash(serialize($posData), $options['apiKey']);
$options['posData'] = json_encode($pos);
if(strlen($options['posData']) > 100)
return array('error' => 'posData > 100 character limit. Are you using the posData hash?');
$options['orderID'] = $orderId;
$options['price'] = $price;
$postOptions = array('orderID', 'itemDesc', 'itemCode', 'notificationEmail', 'notificationURL', 'redirectURL',
'posData', 'price', 'currency', 'physical', 'fullNotifications', 'transactionSpeed', 'buyerName',
'buyerAddress1', 'buyerAddress2', 'buyerCity', 'buyerState', 'buyerZip', 'buyerEmail', 'buyerPhone');
/* $postOptions = array('orderID', 'itemDesc', 'itemCode', 'notificationEmail', 'notificationURL', 'redirectURL',
'posData', 'price', 'currency', 'physical', 'fullNotifications', 'transactionSpeed', 'buyerName',
'buyerAddress1', 'buyerAddress2', 'buyerCity', 'buyerState', 'buyerZip', 'buyerEmail', 'buyerPhone',
'pluginName', 'pluginVersion', 'serverInfo', 'serverVersion', 'addPluginInfo');
*/
// Usage information for support purposes. Do not modify.
//$postOptions['pluginName'] = 'PHP Library';
//$postOptions['pluginVersion'] = '1.3';
//$postOptions['serverInfo'] = htmlentities($_SERVER['SERVER_SIGNATURE'], ENT_QUOTES);
//$postOptions['serverVersion'] = htmlentities($_SERVER['SERVER_SOFTWARE'], ENT_QUOTES);
//$postOptions['addPluginInfo'] = htmlentities($_SERVER['SCRIPT_FILENAME'], ENT_QUOTES);
foreach($postOptions as $o) {
if (array_key_exists($o, $options))
$post[$o] = $options[$o];
}
$post = json_encode($post);
$response = bpCurl('bitpay/api/invoice/';, $options['apiKey'], $post);
if($bpOptions['useLogging']) {
bpLog('Create Invoice: ');
bpLog($post);
bpLog('Response: ');
bpLog($response);
}
return $response;
} catch (Exception $e) {
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return array('error' => $e->getMessage());
}
}
function bpVerifyNotification($apiKey = false) {
global $bpOptions;
try {
if (!$apiKey)
$apiKey = $bpOptions['apiKey'];
$post = file_get_contents("php://input");
if (!$post)
return 'No post data';
$json = json_decode($post, true);
if (is_string($json))
return $json; // error
if (!array_key_exists('posData', $json))
return 'no posData';
$posData = json_decode($json['posData'], true);
if($bpOptions['verifyPos'] and $posData['hash'] != bpHash(serialize($posData['posData']), $apiKey))
return 'authentication failed (bad hash)';
$json['posData'] = $posData['posData'];
return $json;
} catch (Exception $e) {
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return array('error' => $e->getMessage());
}
}
function bpGetInvoice($invoiceId, $apiKey=false) {
global $bpOptions;
try {
if (!$apiKey)
$apiKey = $bpOptions['apiKey'];
$response = bpCurl('bitpay/invoice/'.$invoiceId, $apiKey);
if (is_string($response))
return $response; // error
$response['posData'] = json_decode($response['posData'], true);
$response['posData'] = $response['posData']['posData'];
return $response;
} catch (Exception $e) {
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return 'Error: ' . $e->getMessage();
}
}
function bpHash($data, $key) {
global $bpOptions;
try {
$hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
} catch (Exception $e) {
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return 'Error: ' . $e->getMessage();
}
}
function bpDecodeResponse($response) {
global $bpOptions;
try {
if (empty($response) || !(is_string($response)))
return 'Error: decodeResponse expects a string parameter.';
return json_decode($response, true);
} catch (Exception $e) {
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return 'Error: ' . $e->getMessage();
}
}
function bpCurrencyList() {
global $bpOptions;
$currencies = array();
$rate_url = 'bitpay/rates';;
try {
$clist = json_decode(file_get_contents($rate_url),true);
foreach($clist as $key => $value)
$currencies[$value['code']] = $value['name'];
return $currencies;
} catch (Exception $e) {
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return 'Error: ' . $e->getMessage();
}
}
function bpGetRate($code = 'USD') {
global $bpOptions;
$rate_url = 'bitpay/rates';;
try {
$clist = json_decode(file_get_contents($rate_url),true);
foreach($clist as $key => $value) {
if($value['code'] == $code)
$rate = number_format($value['rate'], 2, '.', '');
}
return $rate;
} catch (Exception $e) {
if($bpOptions['useLogging'])
bpLog('Error: ' . $e->getMessage());
return 'Error: ' . $e->getMessage();
}
}
send.php
$amount = $this->input->post('total_amount');
$id_order = $this->input->post('id_order');
$post_data = array(
'notificationURL' => '/completesubscription/bitpaynotification';,
'id_order' => $this->input->post('id_order')
);
$addl_options = array(
'itemDesc' => $this->input->get('option')
);
$response = bpCreateInvoice($id_order, $amount, $post_data, $addl_options);
if(!empty($response)){
header('Location:'.$response['url'].'');
notification.php
function BitpayNotification()
{
global $bpOptions;
$session_data = $this->session->userdata('logged_in');
echo $bpOptions['apiKey'];
$response = bpVerifyNotification($bpOptions['apiKey']);
$order_id = $response['posData'];
$sessionid = $order_id;
$this->createSubscribe($sessionid,$session_data['id']);
}
redirect.php
$data['method'] = 'bitpay';
$this->load->view('complete_subscribe_view', $data);
Thats please check and let me know if i did anything wrong.
I am using Google’s Calculator API. I have to pass dynamic values to the google url as below:
$url = 'http://www.google.com/ig/calculator?hl=en&q=' . urlEncode($amount . $currency . '=?' . $exchangeIn);
But I am getting the following exception from the google.
Warning: file_get_contents(http://www.google.com/ig/calculator?hl=en&q=13,000,000pkr=?cad) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable in /home/..../public_html/config/config.php on line 48
My function for this is as:
function exchangeRate($amount, $currency, $exchangeIn) {
$url = 'http://www.google.com/ig/calculator?hl=en&q=' . urlEncode($amount . $currency . '=?' . $exchangeIn);
$data = file_get_contents($url);
if(!$data) {
throw new Exception('Could not connect');
}
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$array = $json->decode($data);
if(!$array) {
throw new Exception('Could not parse the JSON');
}
if($array['error']) {
throw new Exception('Google reported an error: ' . $array['error']);
}
return number_format($array['rhs']);
}
echo exchangeRate('9,200,000', 'pkr', 'cad')
Can somebody what is wrong with my code or something wrong with this google api ?
Thanks
I also created currency calculator using Google’s Calculator API like that. Below is my code.
Usage:
simply use your own URL like: yourdomain.com/file.php?from=USD&to=EUR&q=10
The PHP Script:
<?php
session_start();
if(isSet($_GET['from']) && isSet($_GET['to']) && isSet($_GET['q'])) {
$from = preg_replace('/[^A-Z]/','',$_GET['from']);
$to = preg_replace('/[^A-Z]/','',$_GET['to']);
$q = preg_replace('/[^0-9\.]/','',$_GET['q']);
echo currency($from,$to,$q);
}
function currency($from_Currency,$to_Currency,$amount) {
$cookieName = md5("$from_Currency|$to_Currency|$amount");
if(isSet($_COOKIE["$cookieName"])) {
echo $_COOKIE["$cookieName"];
}
else {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , $_SERVER['HTTP_USER_AGENT']);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = html_entity_decode($rawdata);
$data = str_replace(array('lhs','rhs','error','icc',': '),array('"lhs"','"rhs"','"error"','"icc"',':'),$data);
$row = json_decode($data,true);
if(preg_match('/million/',$row['rhs'])) {
$x = 1000000;
}
else if(preg_match('/billion/',$row['rhs'])) {
$x = 1000000000;
}
else {
$x = 1;
}
$result = preg_replace('/[^0-9\.]/','',$row['rhs']);
$kurs = $result * $x;
if($row['icc'] == 'true') {
setcookie("$cookieName", number_format($kurs,2), time()+3600);
return number_format($kurs,2);
}
else {
return "Not available";
}
}
}
?>
Im having problem in importing hotmail contacts from hotmail in php it simple give the erorr message : Error code not found
Please tell me what im doing wrong. I want this to be working.
Im using thew msn_contact_grab.class.php
and iam calling as :
<?php
include('msn_contact_grab.class.php');
$msn2 = new msn;
$returned_emails = $msn2->qGrab("just_4_love01#hotmail.com", "xxxxxxx");
?>
msn_contact_grab.class.php is as follows:
<?php
class msn
{
var $server = 'messenger.hotmail.com';
var $port = 1863;
var $nexus = 'https://nexus.passport.com/rdr/pprdr.asp';
var $ssh_login = 'login.live.com/login2.srf';
var $debug = 0;
var $curl_bin = 0;
var $curl = 'c:/wamp/www/hotmail/curl/curl'; // linux
//var $curl = 'c:\curl.exe'; // windows
//Used to prevent the script from hanging
var $count = 0;
//Used to store the email addresses until all have been collected
var $email_input = array();
var $email_processing = array();
var $email_output = array();
/**
*
* desc : Connect to MSN Messenger Network
*
* in : $passport = passport i.e: user#hotmail.com
* $password = password for passport
*
* out : true on success else return false
*
*/
function connect($passport, $password)
{
$this->trID = 1;
if (!$this->fp = #fsockopen($this->server, $this->port, $errno, $errstr, 2)) {
die("Could not connect to messenger service");
} else {
stream_set_timeout($this->fp, 2);
$this->_put("VER $this->trID MSNP9 CVR0\r\n");
while (! feof($this->fp))
{
$data = $this->_get();
switch ($code = substr($data, 0, 3))
{
default:
echo $this->_get_error($code);
return false;
break;
case 'VER':
$this->_put("CVR $this->trID 0x0409 win 4.10 i386 MSNMSGR 7.0.0816 MSMSGS $passport\r\n");
break;
case 'CVR':
$this->_put("USR $this->trID TWN I $passport\r\n");
break;
case 'XFR':
list(, , , $ip) = explode (' ', $data);
list($ip, $port) = explode (':', $ip);
if ($this->fp = #fsockopen($ip, $port, $errno, $errstr, 2))
{
$this->trID = 1;
$this->_put("VER $this->trID MSNP9 CVR0\r\n");
}
else
{
if (! empty($this->debug)) echo 'Unable to connect to msn server (transfer)';
return false;
}
break;
case 'USR':
if (isset($this->authed))
{
return true;
}
else
{
$this->passport = $passport;
$this->password = urlencode($password);
list(,,,, $code) = explode(' ', trim($data));
if ($auth = $this->_ssl_auth($code))
{
$this->_put("USR $this->trID TWN S $auth\r\n");
$this->authed = 1;
}
else
{
if (! empty($this->debug)) echo 'auth failed';
return false;
}
}
break;
}
}
}
}
//Collects the raw data containing the email addresses
function rx_data()
{
$this->_put("SYN $this->trID 0\r\n");
//Supplies the second MSG code which stops
//the script from hanging as it waits for
//more content
$this->_put("CHG $this->trID NLN\r\n");
$stream_info = stream_get_meta_data($this->fp);
$email_total = 100;
//the count check prevents the script hanging as it waits for more content
while ((! feof($this->fp)) && (! $stream_info['timed_out']) && ($this->count <= 1) && (count($this->email_input) < $email_total))
{
$data = $this->_get();
$stream_info = stream_get_meta_data($this->fp);
if ($data)
{
switch($code = substr($data, 0, 3))
{
default:
// uncommenting this line here would probably give a load of "error code not found" messages.
//echo $this->_get_error($code);
break;
case 'MSG':
//This prevents the script hanging as it waits for more content
$this->count++;
break;
case 'LST':
//These are the email addresses
//They need to be collected in email_input
$this->email_input[] = $data;
if ($this->debug) print("<span class='b'>" . count($this->email_input) . "</span>");
break;
case 'SYN':
$syn_explode = explode(" ", $data);
$email_total = $syn_explode[3];
break;
case 'CHL':
$bits = explode (' ', trim($data));
$return = md5($bits[2].'Q1P7W2E4J9R8U3S5');
$this->_put("QRY $this->trID msmsgs#msnmsgr.com 32\r\n$return");
break;
}
}
}
}
//This function extracts the emails and screen names from the raw data
//collected by rx_data
function process_emails () {
//Neaten up the emails
//$regex = "|^LST\s(\S+?)\s(\S+?)\s\d+?\s\d+?$|";
foreach($this->email_input as $email_entry) {
//Seperate out the email from the name and other data
$this->email_processing[] = explode(" ", $email_entry);
}
//Get rid of the unnecessary data and clean up the name
foreach($this->email_processing as $email_entry){
$this->email_output[] = array(0 => $email_entry['1'],
1 => urldecode($email_entry[2]));
}
//var_dump($this->email_processing);
//var_dump($this->email_output);
}
//This is a quick way of calling all the seperate functions
//needed to grab the contact list
function qGrab ($username, $password) {
//Connect to the MSNM service
$this->connect($username, $password);
//Get data
$this->rx_data();
//Process emails
$this->process_emails();
//send the email array
return $this->email_output;
}
/*====================================*\
Various private functions
\*====================================*/
function _ssl_auth($auth_string)
{
if (empty($this->ssh_login))
{
if ($this->curl_bin)
{
exec("$this->curl -m 60 -LkI $this->nexus", $header);
$header = implode($header, null);
}
else
{
$ch = curl_init($this->nexus);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$header = curl_exec($ch);
curl_close($ch);
}
preg_match ('/DALogin=(.*?),/', $header, $out);
if (isset($out[1]))
{
$slogin = $out[1];
}
else
{
return false;
}
}
else
{
$slogin = $this->ssh_login;
}
if ($this->curl_bin)
{
$header1 = '"Authorization: Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in='.$this->passport.',pwd='.$this->password.','.$auth_string.'"';
exec("$this->curl -m 60 -LkI -H $header1 https://$slogin", $auth_string);
$header = null;
foreach ($auth_string as $key => $value)
{
if (strstr($value, 'Unauthorized'))
{
echo 'Unauthorised';
return false;
}
elseif (strstr($value, 'Authentication-Info'))
{
$header = $value;
}
}
}
else
{
$ch = curl_init('https://'.$slogin);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in='.$this->passport.',pwd='.$this->password.','.$auth_string,
'Host: login.passport.com'
));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$header = curl_exec($ch);
curl_close($ch);
}
preg_match ("/from-PP='(.*?)'/", $header, $out);
return (isset($out[1])) ? $out[1] : false;
}
function _get()
{
if ($data = #fgets($this->fp, 4096))
{
if ($this->debug) echo "<div class=\"r\"><<< $data</div>\n";
return $data;
}
else
{
return false;
}
}
function _put($data)
{
fwrite($this->fp, $data);
$this->trID++;
if ($this->debug) echo "<div class=\"g\">>>> $data</div>";
}
function _get_error($code)
{
switch ($code)
{
case 201:
return 'Error: 201 Invalid parameter';
break;
case 217:
return 'Error: 217 Principal not on-line';
break;
case 500:
return 'Error: 500 Internal server error';
break;
case 540:
return 'Error: 540 Challenge response failed';
break;
case 601:
return 'Error: 601 Server is unavailable';
break;
case 710:
return 'Error: 710 Bad CVR parameters sent';
break;
case 713:
return 'Error: 713 Calling too rapidly';
break;
case 731:
return 'Error: 731 Not expected';
break;
case 800:
return 'Error: 800 Changing too rapidly';
break;
case 910:
case 921:
return 'Error: 910/921 Server too busy';
break;
case 911:
return 'Error: 911 Authentication failed';
break;
case 923:
return 'Error: 923 Kids Passport without parental consent';
break;
case 928:
return 'Error: 928 Bad ticket';
break;
default:
return 'Error code '.$code.' not found';
break;
}
}
}
?>
(moving this from a comment to an answer)
It's probably not that you are doing anything wrong, it's probably just that this class is fishy. The $curl = 'c:/...'; // linux line doesn't instill a lot of confidence. This also seems to be reverse-engineering the messenger protocol, which is a very fragile thing to do.
There seems to be an official API, which you should be using instead: http://dev.live.com/contacts/