$url = $serverHttpHost."/apis/xyz";
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($orderData));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
curl_close ($ch);
How should i call the function in async mode as we are having an script that's take too much time that we need to run in background mode.
Related
I can see that these are the parameters required when I make a call to the payment gateway API, but I have no idea how I would implement this in Javascript (specifically React). Any translators able to lend a hand?
Here is the example code in PHP:
$encryptionKey = 'secret';
$DateTime = new DateTime();
$data = array(
'PAYGATE_ID' => 10011072130,
'REFERENCE' => 'pgtest_123456789',
'AMOUNT' => 3299,
'CURRENCY' => 'ZAR',
'RETURN_URL' => 'https://my.return.url/page',
'TRANSACTION_DATE' => $DateTime->format('Y-m-d H:i:s'),
'LOCALE' => 'en-za',
'COUNTRY' => 'ZAF',
'EMAIL' => 'customer#paygate.co.za',
);
$checksum = md5(implode('', $data) . $encryptionKey);
$data['CHECKSUM'] = $checksum;
$fieldsString = http_build_query($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, 'https://secure.paygate.co.za/payweb3/initiate.trans');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
I have been trying to use axios to make the request, but any method will do. I was trying to create an axios instance like so:
export default axios.create({
baseURL: 'https://secure.paygate.co.za/payweb3/initiate.trans',
headers:{
//I guess this is where PAYGATE_ID etc would go, but I'm not sure how to format it
}
})```
For React, the way to handle this is to generate an MD5 checksum and append it to the payload before sending, probably using CryptoJS or something. I created this function to generate the MD5:
const generateMD5 = (obj, secret = 'paygateSecret') => {
let str = ''
for (let val in obj){
str += obj[val]
}
str += secret
return CryptoJS.MD5(str).toString()
}
I have an object that contains my data:
var data = {
PAYGATE_ID: 10011072130,
REFERENCE: ref,
AMOUNT: amount,
CURRENCY: 'ZAR',
RETURN_URL: window.location.href,
TRANSACTION_DATE: new Date().toISOString(),
LOCALE: 'en-za',
COUNTRY: 'ZAF',
EMAIL: email,
}
Please note the order. It is very important.
Then, I generate the checksum using:
const CHECKSUM = generateMD5(data)
And then make the axios call:
axios.post('https://secure.paygate.co.za/payweb3/initiate.trans', { ...data, CHECKSUM }).then(...).catch(...)
I think this should work!
$scope.formatfilename = response.fileformat[0].FileName;
// it contains filename = abcd
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
echo file_get_contents($siteaddressAPI);
it gives me Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
if I assign full url static to $siteaddressAPI then it gives the result.
how to solve in codeigniter ??
Option 1:
change in php.ini
allow_url_fopen = On
Option 2: use cURL
You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
// make request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $siteaddr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
Working Example
<?php
$siteaddr = "https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY";
// make request
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $siteaddr);
// Execute
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
echo "<pre>", print_r($output), "</pre>";
die();
?>
Output
stdClass Object
(
[error_message] => The provided API key is invalid.
[results] => Array
(
)
[status] => REQUEST_DENIED
)
my urls array contains like 100 urls, and is getting the information from an API designed for something like that.
Anyway, like 50% of the urls returns
400 Bad Request
Your browser sent a request that this server could not understand.
GET /player/euw/Wolves Deficio/ingame HTTP/1.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1
Host: api.captainteemo.com
Accept: */*
the urls are 100% correct, cause when I copy them to my browser, I DO get the info.
Here is my code:
function get_data($urls) {
// spoofing FireFox 2.0
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$ch = curl_init();
// set user agent
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
if(is_array($urls)) {
$output = array();
foreach($urls as $url) {
// set the rest of your cURL options here
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
array_push($output, curl_exec($ch));
}
}
else {
// set the rest of your cURL options here
curl_setopt($ch, CURLOPT_URL, $urls);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
}
// close curl resource to free up system resources
curl_close($ch);
return $output;
}
I added CURLOPT_FOLLOWLOCATION in a case of redirect
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Try this:
<?php
function get_data($urls)
{
if ( !is_array( $urls ) )
$urls = array( '0' => $urls );
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = array();
foreach($urls as $url)
{
curl_setopt($ch, CURLOPT_URL, $url);
$output[$url] = curl_exec($ch);
}
curl_close($ch);
return $output;
}
$urls = array(
'http://www.wikipedia.org/',
'http://www.stackoverflow.com'
);
//or single url
//$urls = 'http://www.stackoverflow.com';
print_r ( get_data($urls) );
The problem was that I spoofed the user agent instead of using a real one, also didnt repalced " " by "+".
I am trying to implement a batch process for the doCapture API from paypal. I have the code below and it only processes the first record of the database...Help!!
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
<?php
include("xxxxx.php");<---- this is just the database connection
$query2="SELECT *
FROM x where payment_status = 'Pending'";
// WHERE custom IN (
// SELECT custom
// FROM x
// GROUP BY custom
// HAVING count(custom) > 1
// )
//ORDER BY custom";
$results=mysql_query($query2);
$row2 = mysql_fetch_array($results);
$row_count=mysql_num_rows($results);
echo $row_count;
//$auth=$row2['auth_id'];
//while($row2 =mysql_fetch_array($results)){
$arrSize=sizeof($row_count);
for ($number = 0; $number < $arrSize; $number++) {
//for($i=0; $i<$row_count; $i++){
echo $row2['auth_id']; // prints hello
//echo $row2['auth_id'];
/** DoCapture NVP example; last modified 08MAY23.
*
* Capture a payment.
*/
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
//for($i=0; $i<$row_count; $i++){
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('');
$API_Password = urlencode('');
$API_Signature = urlencode('.');
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
// Set request-specific fields.
$authorizationID = urlencode($row2['auth_id']);
$amount = urlencode('1.99');
$currency = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$completeCodeType = urlencode('Complete'); // or 'NotComplete'
$invoiceID = urlencode('example_invoice_id');
$note = urlencode('example_note');
// Add request-specific fields to the request string.
$nvpStr="&AUTHORIZATIONID=$authorizationID&AMT=$amount&COMPLETETYPE=$completeCodeType&CURRENCYCODE=$currency&NOTE=$note";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoCapture', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Capture Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoCapture failed: ' . print_r($httpParsedResponseAr, true));
//}
}}
//}
?>
You're only fetching one row out of the database, because your $row2 = mysql_fetch_array($results); line is outside of your for loop. Essentially, you're trying to capture the same payment over and over again, and I'm willing to bet that only the first one is succeeding. Move the fetch statement to just inside the for loop.
Firstly, How would you get Google Alerts information into a database other than to parse the text of the email message that Google sends you?
It seems that there is no Google Alerts API.
If you must parse text, how would you go about parsing out the relevant pieces of the email message?
When you create the alert, set the "Deliver To" to "Feed" and then you can consume the feed XML as you would any other feed. This is much easier to parse and digest into a database.
class googleAlerts{
public function createAlert($alert){
$USERNAME = 'XXXXXX#gmail.com';
$PASSWORD = 'YYYYYY';
$COOKIEFILE = 'cookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);
$formFields = $this->getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
if (strpos($result, '<title>') === false) {
return false;
} else {
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/create');
curl_setopt($ch, CURLOPT_POST, 0);
$result = curl_exec($ch);
//var_dump($result);
$result = $this->getFormFieldsCreate($result);
$result['q'] = $alert;
$result['t'] = '7';
$result['f'] = '1';
$result['l'] = '0';
$result['e'] = 'feed';
unset($result['PersistentCookie']);
$post_string = '';
foreach($result as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/manage');
$result = curl_exec($ch);
if (preg_match_all('%'.$alert.'(?=</a>).*?<a href=[\'"]http://www.google.com/alerts/feeds/([^\'"]+)%i', $result, $matches)) {
return ('http://www.google.com/alerts/feeds/'.$matches[1][0]);
} else {
return false;
}
}
}
private function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
private function getFormFieldsCreate($data)
{
if (preg_match('/(<form.*?name=.?.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form1');
}
}
private function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
}
$alert = new googleAlerts;
echo $alert->createAlert('YOUR ALERT');
It will return link to rss feed of your newly created alert
I found a Google Alerts API here. It's pretty minimal and I haven't tested it.