I can access this script directly via URL and it works fine but as a cron job ot doesnt work. Is it aweber or am I doing something wrong?
Awebre's documentation is one of the worst ones I have ever come across!
I am not sure why there is no explanation of this in their docs!
Thanks
<?php
include "wp-load.php";
include_once('wp-includes/class-phpass.php');
$sql = "SELECT member_id, email FROM wp_members_tbl WHERE aweber != 1";
$result = $wpdb->get_results($sql);
if(count($result)>0)
{
##Add aweber
require_once('aweber/aweber_api/aweber_api.php');
$consumerKey = '***';
$consumerSecret = '***';
$accessKey = '***'; # put your credentials here
$accessSecret = '***'; # put your credentials here
$account_id = '***'; # put the Account ID here
$list_id = '***'; # put the List ID here 3823593
$aweber = new AWeberAPI($consumerKey, $consumerSecret);
# Get an access token
if(empty($_COOKIE['accessToken']))
{
if (empty($_GET['oauth_token']))
{
$callbackUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
list($requestToken, $requestTokenSecret) = $aweber->getRequestToken($callbackUrl);
setcookie('requestTokenSecret', $requestTokenSecret);
setcookie('callbackUrl', $callbackUrl);
header("Location: {$aweber->getAuthorizeUrl()}");
exit();
}
$aweber->user->tokenSecret = $_COOKIE['requestTokenSecret'];
$aweber->user->requestToken = $_GET['oauth_token'];
$aweber->user->verifier = $_GET['oauth_verifier'];
list($accessToken, $accessTokenSecret) = $aweber->getAccessToken();
setcookie('accessToken', $accessToken);
setcookie('accessTokenSecret', $accessTokenSecret);
header('Location: '.$_COOKIE['callbackUrl']);
exit();
}
##End add aweber
foreach($result as $val=>$row)
{
# Get AWeber Account
try {
$account = $aweber->getAccount($_COOKIE['accessToken'], $_COOKIE['accessTokenSecret']);
$listURL = "https://api.aweber.com/1.0/accounts/***/lists/".$list_id;
$list = $account->loadFromUrl($listURL);
$params = array(
'email' => $row->email
);
$subscribers = $list->subscribers;
$new_subscriber = $subscribers->create($params);
$update_data = array('aweber' => 1);
$where = array('member_id' => $row->member_id);
$wpdb->update( 'wp_members_tbl', $update_data, $where, $format = null, $where_format = null);
# success!
//print "A new subscriber was added to the $list->name list!";
}
catch(AWeberAPIException $exc)
{
print "<h3>AWeberAPIException:</h3>";
print " <li> Type: $exc->type <br>";
print " <li> Msg : $exc->message <br>";
print " <li> Docs: $exc->documentation_url <br>";
print "<hr>";
//exit(1);
}
}
}
Looks like a few places where this could be failing:
1) You have relative paths in your includes. The cron may not be able to find the included files. Try changing these to full paths.
2) Your code requires a browser environment (setting cookies, http header Location etc). None of this will work outside of a browser.
You should always execute the file from the command line as the user the cron runs as to test it. Any errors will be obvious.
To fix your issue you should use this tutorial which uses the browser to setup the credentials. After that it can be run from the command line/cron:
http://engineering.aweber.com/quick-start-api-script-in-php/
Try using this in the cron command:
wget -qO- http://yoururlhere/ &> /dev/null
It's not the best solution since "self calls" aren't recommended, but it'll keep you from dealing with environment settings.
Related
I want to use shopify order webhook to store order data into mysql database. I am beginner in webhooks. Googled many times to find the guidance about how to achieve it.I found this solutions is very close for me.I wrote the php code but I am getting error like this error img.I don't know why I am getting this error and how to resolve it.Please suggest us.
I followed these steps
I created the webhook from shopify admin dashboard
Point the webhook to my own domain
And write the following code in the pointed link
here is my code
my code is
<?php
$webhook_content = NULL;
// Get webhook content from the POST
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhook_content .= fread($webhook, 4096);
}
fclose($webhook);
// Decode Shopify POST
$webhook_content = json_decode($webhook_content, TRUE);
$servername = "localhost";
$database = "xxxxxxxx_xxxhalis";
$username = "xxxxxxxx_xxxhalis";
$password = "***********";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$order_num= $webhook_content['name'];
$order_date = $webhook_content['created_at'];
$order_mode = "Online";
$location= $webhook_content['default_address']['province'];
$cust_name = $webhook_content['billing_address']['name'];
$address = $webhook_content['default_address']['address1']['address2']['city']['province']['zip'];
$phone_num = $webhook_content['default_address']['phone'];
$special_note= $webhook_content['note'];
$total_mrp = $webhook_content['current_subtotal_price'];
$total_discount= $webhook_content['current_total_discounts'];
$sub_total = $webhook_content['current_subtotal_price'];
$delivery_charges = $webhook_content['presentment_money']['amount'];
$totalOrderValues= $webhook_content['total_price'];
$discount_approval = "NA";
$invoice_status= "NA";
$punching_status = "NA";
$order_source = "Shopify";
$payment_mode= $webhook_content['payment_gateway_names'];
$payement_status = "Done";
$payement_recieve_date= $webhook_content['processed_at'];
$reference_number = $webhook_content['reference'];
$cash_handover_status = "NA";
$my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO `customer_order_sab`( `order_num`, `order_datetime`, `modeOfOrder`, `location`, `customer_name`, `address`, `phone_number`, `special_note`, `total_mrp`, `total_discount`, `sub_total`, `delivery_charges`, `totalOrderValues`, `discount_approval`, `invoice_status`, `punching_status`, `order_source`, `payment_mode`, `payement_status`, `payement_recieve_date`, `reference_number`, `cash_handover_status`) VALUES (:order_num, :order_date, :order_mode, :location, :cust_name, :address, :phone_num, :special_note, :total_mrp, :total_discount, :sub_total, :delivery_charges, :totalOrderValues, :discount_approval, :invoice_status, :punching_status, :order_source, :payment_mode, :payement_status, :payement_recieve_date, :reference_number, :cash_handover_status)");
$my_Insert_Statement->bindParam(':order_num', $order_num);
$my_Insert_Statement->bindParam(':order_date', $order_date);
$my_Insert_Statement->bindParam(':order_mode', $order_mode);
$my_Insert_Statement->bindParam(':location', $location);
$my_Insert_Statement->bindParam(':cust_name', $cust_name);
$my_Insert_Statement->bindParam(':address', $address);
$my_Insert_Statement->bindParam(':phone_num', $phone_num);
$my_Insert_Statement->bindParam(':special_note', $special_note);
$my_Insert_Statement->bindParam(':total_mrp', $total_mrp);
$my_Insert_Statement->bindParam(':total_discount', $total_discount);
$my_Insert_Statement->bindParam(':sub_total', $sub_total);
$my_Insert_Statement->bindParam(':delivery_charges', $delivery_charges);
$my_Insert_Statement->bindParam(':totalOrderValues', $totalOrderValues);
$my_Insert_Statement->bindParam(':discount_approval', $discount_approval);
$my_Insert_Statement->bindParam(':invoice_status', $invoice_status);
$my_Insert_Statement->bindParam(':punching_status', $punching_status);
$my_Insert_Statement->bindParam(':order_source', $order_source);
$my_Insert_Statement->bindParam(':payment_mode', $payment_mode);
$my_Insert_Statement->bindParam(':payement_status', $payement_status);
$my_Insert_Statement->bindParam(':payement_recieve_date', $payement_recieve_date);
$my_Insert_Statement->bindParam(':reference_number', $reference_number);
$my_Insert_Statement->bindParam(':cash_handover_status', $cash_handover_status);
if ($my_Insert_Statement->execute()) {
echo "New record created successfully";
} else {
echo "Unable to create record";
}
?>
You are doing it wrong in one giant respect, but I respect you for trying!
If you expect webhooks to be sent to your App from some store where you installed your App, and you expect to save data from the webhooks in your database you cannot create the webhooks from the Shopify Admin and then process them in your App due to security. Instead, you install a webhook from your App, instructing Shopify to send your App webhooks. This way, Shopify can use your App API token to secure the webhooks. Your App then receives webhooks and decides if they are legit or not. You cannot do that if you use the Admin.
Read up on creating webhooks for use with your App! You can choose RestAPI or GraphQL and go from there.
In the last one week and a half, I've been looking for an answer on the question: how do I get my payment API to work?
I have a test account with the Danish payment gateway provider ePay/Bambora.
I have no problem getting the JavaScript version to Work, but I'd like to do the payment by an PHP-api, to make sure I have full control on which information is hidden for people who don't need to see it, information such as my "MerchantID".
ePay/Bambora seems to be very scarce with their information on how to fulfill a payment by PHP, or else I might be blind (or can't see the forest before the trees).
This is the code I've been written:
<?php
$epay_params['merchantnumber'] = "1234567"; //fake ID
$epay_params['transactionid'] = "-1";
$epay_params['amount'] = "9995";
$epay_params['group'] = "-1";
$epay_params['paymentcollection'] = "1";
$epay_params['orderid'] = "-1";
$epay_params['pbsResponse'] = "-1";
$epay_params['epayresponse'] = "-1";
$client = new SoapClient('https://ssl.ditonlinebetalingssystem.dk/remote/payment.asmx?WSDL');
$result = $client->capture($epay_params);
if($result->captureResult == true){
echo "Result OK"; //Capture OK
}
else{
echo json_encode( $result );
}
?>
This gives the following result: {"captureResult":false,"pbsResponse":-1,"epayresponse":-1008}
According to ePay/Bambora does -1008 mean, that the transactionid isn't found.
This seems to be correct, since there is no transaction called -1. I want to create a NEW payment, so I don't have a transaction id yet.
So either I have to create a transactionid on ePay/Bamboras server BEFORE I run the payment (how?) or I should not use the method "capture", but which method should I use then?
To be clear: I am not making a webshop, but just a payment system on my new calendar webapp.
The Question is: How do I fulfill a single payment via ePay/Bambora in PHP?
Try this http_build_query() for make URL perfectly
<?php
$url = 'https://ssl.ditonlinebetalingssystem.dk/remote/payment.asmx';
$params = array('WSDL');
$url .= '?' . http_build_query($params);
$epay_params['merchantnumber'] = "1234567"; //fake ID
$epay_params['transactionid'] = "-1";
$epay_params['amount'] = "9995";
$epay_params['group'] = "-1";
$epay_params['paymentcollection'] = "1";
$epay_params['orderid'] = "-1";
$epay_params['pbsResponse'] = "-1";
$epay_params['epayresponse'] = "-1";
$client = new SoapClient($url);
$result = $client->capture($epay_params);
if($result->captureResult == true){
echo "Result OK"; //Capture OK
}
else{
echo json_encode( $result );
}
?>
Hope this work either knock me
I"m using below third party code to send SMS for customers who are making orders in my web store, it seems this code is loading slowly and it's causing my order confirmation page (which has this code inside) to load slow.
is there any solution that I can use this code but it's slowness don't affect my page ?
Thanks
// Send SMS
/*
ini_set("soap.wsdl_cache_enabled", "0");
$sms_client = new SoapClient('http://87.107.121.54:2620/post/send.asmx', array('encoding'=>'UTF-8'));
$parameters['username'] = "xxxxxxxxxxx";
$parameters['password'] = "xxxx";
$parameters['to'] = "$phone";
$parameters['from'] = "1000947320";
$parameters['text'] ="test";
$parameters['isflash'] =false;
$sms_client->SendSimpleSMS2($parameters)->SendSimpleSMS2Result;
*/
Make the confirmation page add the values into database and create a script which processes the values from the database, meaning:
when user enters the page, your code will do something like this:
INSERT INTO sms SET to='$to', text='$text', sent=0;
and then you make a script which does the following:
ini_set("soap.wsdl_cache_enabled", "0");
$parameters['username'] = "xxxxxxxxxxx";
$parameters['password'] = "xxxx";
$parameters['from'] = "1000947320";
$parameters['isflash'] =false;
$sms_client = new SoapClient('http://87.107.121.54:2620/post/send.asmx', array('encoding'=>'UTF-8'));
$query = mysql_query("SELECT * FROM sms WHERE sent=0");
while( $message = mysql_fetch_assoc($query) ) {
$thisMessage = $parameters;
$thisMessage['to'] = $message['to'];
$thisMessage['text'] = $message['text'];
$sms_client->SendSimpleSMS2($thisMessage)->SendSimpleSMS2Result;
mysql_query('UPDATE sms SET sent=1 WHERE id='.$message['id']);
}
and you run this script in cron, lets say every minute or how often do you want to.
My code:
<?php
if(isset($_GET['login']) && isset($_GET['login']) && isset($_GET['password'])){
$_login_url = "http://testing.wialon.com/wialon/ajax.html?svc=core/login¶ms={user:%s,password:%s}";
$login = $_GET['login'];
$password = $_GET['password'];
$handle = fopen(sprintf($_login_url, $login, $password), "r");
$line = fgets($handle);
fclose($handle);
$responce = explode(",",$line);
if(count($responce) < 2) {
echo "Invalid user or password";
} else {
$sessid = explode(":",$responce[1]);
$lastid = str_replace("\"","",$sessid[1]);
echo "http://testing.wialon.com/index.html?sid=".$lastid."";
}
}
?>
when I access this script with the server hosting the script everything works perfectly, The sessions are generated with my IP address.
But when I access it with another computer any user trying to login the script generates session using the servers IP address. can I send the request with the users IP address?
No, you cannot send the request with the users IP address.
However, you might be able to indicate that the request is being performed on behalf of another IP by using the HTTP_X_FORWARDED_FOR request header or similar, but without looking at their documentations (which doesn't seem to be publicly available) I can't be sure of it. You'll need to ask 'em.
This is an old thread but, let me put in my two cents. There are two new wialon athentication methods Token login and by passing the athorization hash . the second method is best suited for maintaining session across servers.
http://sdk.wialon.com/wiki/en/kit/remoteapi/apiref/core/create_auth_hash
http://sdk.wialon.com/wiki/en/kit/remoteapi/apiref/token/token
//get the Token from here http://hosting.wialon.com/login.html?client_id=wialon&access_type=-1&activation_time=0&duration=0&flags=1
// You should have your existing username from wialon with SDK access
$params = "{'token':'$token','operateAs','$username'}";
$baseurl = "http://hst-api.wialon.com/wialon/ajax.html";
$url = "$baseurl?params=".urlencode($params)."&svc=token/login";
$o = json_decode(file_get_contents($url),true);
$sid = $o['eid'];
I am building an app using Abraham William's TwitterOAuth Package. The app is working fine, except I am running into one problem.
About the 25% of the users who try to install the app cannot do so. They verify the application on the Twitter Page and click "Sign In" (on Twitter's website). When they are referred back to the Callback.php page, it gives them a blank page. I cannot figure out what is wrong, because it works for most users. Any ideas?
Here is the callback.php code:
<?php
require_once("config_db.php");
session_start();
// Include class & create
require_once("consumer-keys.php");
require_once("twitteroauth/twitteroauth/twitteroauth.php");
// User has selected to DENY access
if(!empty($_GET["denied"])) {
// could re-direct or display cancelled view/template
// we're just echoing out a message
echo "No deal! <a href='login.php'>Try again?</a>";
die();
}
// User has selected to ALLOW access for given token
if($_GET["oauth_token"] == $_SESSION["oauth_token"]) {
// Use generated request tokens (from session) to construct object
$tOAuth = new TwitterOAuth($consumerKey, $consumerSecret, $_SESSION["oauth_token"], $_SESSION["oauth_token_secret"]);
// Retrieve access token from Twitter
$accessToken = $tOAuth->getAccessToken();
//echo "RECEIVED TOKENS<br>";
// Check we have valid response
if(is_numeric($accessToken["user_id"])) {
// Save the access tokens to a DB (we're using a session)
$_SESSION["access_token"] = $accessToken;
//GET CREDENTIALS VIA API
$credentials = $tOAuth->get('account/verify_credentials');
//echo "HAS NUMERIC ID<br>";
//ISAAC ADD DB INFO
$query = "SELECT * FROM `t4i_app`.`users_twitter` WHERE user_id = '".$_SESSION["access_token"]["user_id"]."'";
$rs = mysql_query($query);
if(mysql_num_rows($rs)) {
//update query
//echo "user already exists..need to update";
$query = "UPDATE `t4i_app`.`users_twitter` SET `token` = '".$_SESSION["access_token"]["oauth_token"]."', `secret` = '".$_SESSION["access_token"]["oauth_token_secret"]."', `screen_name` = '".$credentials->screen_name."', `followers` = '".$credentials->followers_count."' WHERE `users_twitter`.`user_id` = '".$_SESSION["access_token"]["user_id"]."';";
mysql_query($query);
} else {
$query = "INSERT INTO `t4i_app`.`users_twitter` (`id` ,`screen_name` ,`token` ,`secret`, `user_id`, `followers`, `referer` ,`last_update` ,`date_registered`) VALUES (NULL, '".$credentials->screen_name."', '".$_SESSION["access_token"]["oauth_token"]."', '".$_SESSION["access_token"]["oauth_token_secret"]."', '".$_SESSION["access_token"]["user_id"]."', '".$credentials->followers_count."', '0', CURRENT_TIMESTAMP , CURRENT_TIMESTAMP);";
mysql_query($query);
}
//echo $query;
//echo mysql_error();
//print_r($_SESSION["access_token"]);
$message = array('status' => 'Test OAuth update. #testoauth');
$test = $tOAuth->post('statuses/update', array('status' => 'I just added the new APPNAME Twitter Application http://bit.ly/sampleurl'));
//echo "POSTED STATUS<br>";
//END ISAAC
// Remove request token session variables
unset($_SESSION["oauth_token"]);
unset($_SESSION["oauth_token_secret"]);
// Redirect to main page
header("location: http://www.mydomain.com/welcome.php");
} else {
//echo "TRYING TO REDIRECT <br>";
header("location: http://www.mydomain.com");
}
}
?>
if ($_GET["oauth_token"] == $_SESSION["oauth_token"])
You'll want to put an error_log in the else for this, you're failing without any messages if the oauth_tokens in the get and session don't match. It could be that Twitter isn't responding properly.
Also, I would capitalize the Location in the header call. I'm not 100% that every browser will honor it when it's not Location: