I'm trying to show SMS balance using an API in a PHP page.
What am I missing to simplify this? (The API is working fine directly):
public function show_sms_credits() {
if ( false === ( $my_query = get_transient( 'available_sms_credits' ) ) ) {
$api_key = get_option( 'wc_api_key', true );
$api_token = get_option( 'wc_api_token', true );
if( empty ( $api_key ) || empty( $api_token ) ){
return;
}
$url = 'http://mywebsite.com/api/';
$response = wp_remote_get("{$this->url}GetBalance?User={$this->api_key}&Password={$this->api_token}");
if( ! is_wp_error( $response ) && 200 == wp_remote_retrieve_response_code( $response ) ) {
$body = json_decode( wp_remote_retrieve_body( $response ) );
set_transient( 'available_sms_credits', $body->sms_credits, 12 * HOUR_IN_SECONDS );
}
}
$sms_credits = get_transient( 'available_sms_credits' );
}
}
<p> SMS Balance: <?php echo 'available_sms_credits': ?> </p>
Because you use this syntax
$url = 'http://mywebsite.com/api/';
You should simply use
$response = wp_remote_get("{$url}GetBalance?User={$api_key}&Password={$api_token}");
Because you've only assigned local variables, not assignments to the current object itself. If you needed to add the URL as a property against your object you'd have use $this like...
$this->url = 'http://mywebsite.com/api/';
Also your're not doing anything with $sms_credits
Related
I need to interact with a third party plugin to send SMS. The plugin is Bookly, which is for making appointments. I edited the Ajax.php that Bookly uses for saving the appointment. I've sent the SMS succesfully on Ajax.php. However, I want to code an external plugin to make the process controllable on admin panel.
I use a custom hook named "bookly_appointment_saved" and send an array with that. And in my new plugin I catch the hook succesfully. The SMS is always sent but the Ajax.php of Bookly doesn't send the response to the frontend. It keeps showing the page as loading.
Please see the codes below and help.
Ajax.php (Bookly) - Only related method is included.
/**
* Save cart appointments.
*/
public static function saveAppointment()
{
$userData = new Lib\UserBookingData( self::parameter( 'form_id' ) );
if ( $userData->load() ) {
$failed_cart_key = $userData->cart->getFailedKey();
if ( $failed_cart_key === null ) {
$cart_info = $userData->cart->getInfo();
$is_payment_disabled = Lib\Config::paymentStepDisabled();
$skip_payment = BookingProxy\CustomerGroups::getSkipPayment( $userData->getCustomer() );
$gateways = self::getGateways( $userData, clone $cart_info );
if ( $is_payment_disabled || isset( $gateways['local'] ) || $cart_info->getPayNow() <= 0 || $skip_payment ) {
// Handle coupon.
$coupon = $userData->getCoupon();
if ( $coupon ) {
$coupon->claim()->save();
}
// Handle payment.
$payment = null;
if ( ! $is_payment_disabled && ! $skip_payment ) {
if ( $cart_info->getTotal() <= 0 ) {
if ( $cart_info->withDiscount() ) {
$payment = new Lib\Entities\Payment();
$payment
->setType( Lib\Entities\Payment::TYPE_FREE )
->setStatus( Lib\Entities\Payment::STATUS_COMPLETED )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( 0 )
->setPaid( 0 )
->save();
}
} else {
$payment = new Lib\Entities\Payment();
$status = Lib\Entities\Payment::STATUS_PENDING;
$type = Lib\Entities\Payment::TYPE_LOCAL;
$paid = 0;
foreach ( $gateways as $gateway => $data ) {
if ( $data['pay'] == 0 ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$type = Lib\Entities\Payment::TYPE_FREE;
$cart_info->setGateway( $gateway );
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
break;
}
}
if ( $status !== Lib\Entities\Payment::STATUS_COMPLETED ) {
$gift_card = $userData->getGiftCard();
if ( $gift_card ) {
$type = Lib\Entities\Payment::TYPE_CLOUD_GIFT;
$cart_info->setGateway( $type );
if ( $gift_card->getBalance() >= $cart_info->getPayNow() ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$paid = $cart_info->getPayNow();
$gift_card->charge( $paid )->save();
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
}
}
}
$payment
->setType( $type )
->setStatus( $status )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( $cart_info->getTotal() )
->setTax( $cart_info->getTotalTax() )
->setPaid( $paid )
->save();
}
}
// Save cart.
$order = $userData->save( $payment );
if ( $payment !== null ) {
$payment->setDetailsFromOrder( $order, $cart_info )->save();
}
// Send notifications.
Lib\Notifications\Cart\Sender::send( $order );
$response = array(
'success' => true,
);
} else {
$response = array(
'success' => false,
'error' => Errors::PAY_LOCALLY_NOT_AVAILABLE,
);
}
} else {
$response = array(
'success' => false,
'failed_cart_key' => $failed_cart_key,
'error' => Errors::CART_ITEM_NOT_AVAILABLE,
);
}
//Custom hook
$user_appointed=$userData->getData();
do_action('bookly_appointment_saved',
$appointment=[
'date'=>date("d/m/Y", strtotime($user_appointed['slots'][0][2]) ),
'time'=>date("H:i", strtotime($user_appointed['slots'][0][2]) ),
'full_name'=>$user_appointed['full_name']=''?$user_appointed['first_name'].' '.$user_appointed['last_name']:$user_appointed['full_name'],
'service_name'=>$userData->cart->getItemsTitle(),
]
);
// end of hook
$userData->sessionSave();
wp_send_json( $response );
}
Errors::sendSessionError();
}
custom-sms-sender-plugin.php (My plugin)
add_action('bookly_appointment_saved','send_sms');
function send_sms($appointment){
$phone = "66666666666";
$message="New appointment - ".$appointment['full_name']." Service: ".$appointment['service_name']." Date: ".$appointment['date']." Time:".$appointment['time'];
$message = urlencode($message);
$url= "//request url with parameters";
$request = wp_remote_get($url);
if ($request['body'] !=30 || $request['body'] !=20 || $request['body'] !=40 || $request['body'] !=50 || $request['body'] != 51 || $request['body'] != 70 || $request['body'] != 85) {
write_log("SENT - SMS Code : ".explode(" ",$request['body'])[1]);
} else {
write_log("ERROR - Code : ".$request['body']);
}
}
I've solved the problem. It is caused by the "write_log" commands as the command doesn't exist. After changing the log method, it worked like a charm. Thanks for all comments.
I am currently working with Accessing json using php in wordpress. I have successfully decoded the json but when i try to access the values it doesn't fetch . I am trying to access the Cluster_ID and Image
values.
Here's my api link http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news
I have tried the following code:
<?php
/**
*Plugin Name: plugin two
**/
function myjson8(){
$request = wp_remote_get( 'http://ec2-13-127-149-66.ap-south-1.compute.amazonaws.com:5000/api/news' );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
if( ! empty( $data) ) {
foreach( $data as $product ) {
echo $product->Cluster_ID;
foreach($data->data as $news){
echo $news->Image;
}
}
}
}
Taking the data from the news feed that you supplied then placing it in a JSON viewer you get:
On opening level 0 we get
This is not what you want so we need to look at level 1 and its structure
So your code would be:
for($x=0; $x<count($data[1]); $x++ ) {
$clusterId = $data[1][$x]['Cluster_ID'];
for( $p=0; $p<count( $data[1][$x]['data'] ); $p++ ) {
$pic = $data[1][$x]['data'][$p];
}
}
So I am working with the coinmarketcap api and try to combinate it with WordPress.
In WordPress I am using the following php code:
function api() {
$url = 'https://api.coinmarketcap.com/v1/ticker/?start=0&limit=250';
$response = wp_remote_get( esc_url_raw( $url ) );
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
$name = $api_response[1]["name"];
$usd = $api_response[1]["price_usd"];
echo $name . "<br />";
echo $usd;
}
add_shortcode( 'api_short', 'api' );
So this code is working and I get my results on the WordPress page by using the shortcode api_short.
My problem now is that I want to use the shortcode on the following way:
[api short name ="20"]
This way I can switch from data easily by only using the shortcode instead of changing the code the whole time.
The 'name' variable in this case is the name of the cryptocurrency as can be seen here: https://api.coinmarketcap.com/v1/ticker/?start=0&limit=250 . 0 = bitcoin , 1 = ethereum.
I hope someone knows a way to get this working, I tried somethings but so far without a result.
The WordPress shortcode documentation can be found here: https://codex.wordpress.org/Shortcode_API
A few things:
First:
Prefix your functions - especially if you're using a name that's got a global scope or appeal.
api() should really be something along the lines of solaiman_api() to prevent any conflicts.
Second:
You should be using the WP Transients API to cache results so you don't rate limit the CMC API
Third:
For the actual answer to your question, you just need to parameterize the input value in the URL.
function solaiman_api( $atts ) {
extract( shortcode_atts( array(
'placeholder' => ''
), $atts ) );
$coin = $atts['coin'] ? $atts['coin'] : 0; // Default to 0 for BTC
$limit = $atts['limit'] ? $atts['limit'] : 250; // Default to 250
$url = 'https://api.coinmarketcap.com/v1/ticker/?start='. $coin .'&limit='. $limit;
$response = wp_remote_get( esc_url_raw( $url ) );
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
foreach( $api_response as $c ){
echo $c['name'].': $'.$c['price_usd'].'<br />';
}
}
add_shortcode( 'cmc_api', 'solaiman_api' );
Note I changed your function name and the shortcode, since api_short isn't terribly descriptive.
This shortcode would now look like this:
[cmc_api coin="1" limit="1"]
Which should give you just the price of Ethereum.
Use This Code Instead:
Here's a better one that caches the results for 10 minutes according to CMC's terms of service:
function solaiman_api( $atts ) {
extract( shortcode_atts( array(
'placeholder' => ''
), $atts ) );
$coin = $atts['coin'] ? $atts['coin'] : 0; // Default to 0 for BTC
$limit = $atts['limit'] ? $atts['limit'] : 250; // Default to 250
$url = 'https://api.coinmarketcap.com/v1/ticker/?start='. $coin .'&limit='. $limit;
$transient_name = 'cmc_api_'.$coin.'_'.$limit; // One transient per coin per limit
if( false === ( $response = get_transient( $transient_name ) ) ){
$response = wp_remote_get( esc_url_raw( $url ) );
set_transient( $transient_name, $response, 600 ); // Cache for 10 minutes
}
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
foreach( $api_response as $c ){
echo $c['name'].': $'.$c['price_usd'].'<br />';
}
}
add_shortcode( 'cmc_api', 'solaiman_api' );
You can see an example of [cmc_api coin="1" limit="1"] here: http://xhynk.com/headless/2018/02/28/cmc-test/
I'm trying to use the following the code
$response = wp_remote_post( 'https://domain.com/forms/3/input', $args );
if( ! is_wp_error( $response ) ) {
$result = json_decode( $response['body'] );
update_field( 'dk_id', $result->result->id, $post->ID );
}
Somehow the meta is not saved to the database. $result->result->id is an integer when using gettype().
This code is working for me just fine though:
$response = wp_remote_post( 'https://domain.com/forms/3/input', $args );
if( ! is_wp_error( $response ) ) {
$result = json_decode( $response['body'] );
update_field( 'dk_id', 'TEST', $post->ID );
}
It looks like the function won't take my variable. Thanks a bunch for helping out!
I have been using the following script to create sitemaps for my clients websites. The issue is it does not work for every site. I have found that many if not all the sites hosted on godaddy do not spider. If anyone can see an error in my script or know what is causing the fault I would greatly appreciate the help.
Thanks in advance
set_time_limit(0);
class spider_man
{
var $url;
var $limit;
var $cache;
var $crawled;
var $banned_ext;
var $domain;
function spider_man( $url, $banned_ext, $limit ){
$this->domain = $url;
$this->url = 'http://'.$url ;
$this->banned_ext = $banned_ext ;
$this->limit = $limit ;
if( !fopen( $this->url, "r") ) return false;
else $this->_spider($this->url);
}
function _spider( $url ){
$this->cache = #file_get_contents( urldecode( $url ) );
if( !$this->cache ) return false;
$this->crawled[] = urldecode( $url ) ;
preg_match_all( "#href=\"(https?://[&=a-zA-Z0-9-_./]+)\"#si", $this->cache, $links );
if ( $links ) :
foreach ( $links[1] as $hyperlink ){
if(strpos($hyperlink,$this->domain)===false){ break; }
else{
$this->limit--;
if( ! $this->limit ) return;
if( $this->is_valid_ext( trim( $hyperlink ) ) and !$this->is_crawled( $hyperlink ) ) :
$this->crawled[] = $hyperlink;
echo "Crawling $hyperlink<br />\n";
unset( $this->cache );
$this->_spider( $hyperlink );
endif;
}
}
endif;
}
function is_valid_ext( $url ){
foreach( $this->banned_ext as $ext ){
if( $ext == substr( $url, strlen($url) - strlen( $ext ) ) ) return false;
}
return true;
}
function is_crawled( $url ){
return in_array( $url, $this->crawled );
}
}
$banned_ext = array(".dtd",".css",".xml",".js",".gif",".jpg",".jpeg",".bmp",".ico",".rss",".pdf",".png",".psd",".aspx",".jsp",".srf",".cgi",".exe",".cfm");
$spider = new spider_man( 'domain.com', $banned_ext, 100 );
print_r( $spider->crawled );
When you access a site using fopen() of file_get_contents() you don't send AGENT or REFERRER or other header information. It's blatently obvious that this is an automated script.
You need to look at sending context with your fopen (check the docs and read the context section) or, better still, using CURL. This allows you to set the agent and referrer headers to simulate a browser.