I´m forking this repo https://github.com/FundacionPesetacoin/Pesetacoin_WooCommerce-Plugin and working fine. But when change the API for catch the price in other Site, not update
I try some differents links of API and make same.
Original code get info of his private API, and I want use other public API.
With original code, API show this info:
{"status" : "success" , "message" : "null", "ptc_btc" : "0.00000083", "btc_usd" : "5070.29", "btc_eur" : "4505.46", "supply" : "138188628.56442260", "ptc_eur" : "0.00373953", "ptc_usd" : "0.00420834" , "date" : "2019-04-13 10:20:07"}
and get "ptc_eur" of API for shows in shoppping cart.
Now I want use the new API of other site https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur than shows this info:
{"reecore":{"eur":0.0046564}}
I want use only the "eur" data , same the original code use the "ptc_eur" but dont work.
Sorry for my english.
ORIGINAL CODE:
//precio en PesetaCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "http://nodos.pesetacoin.info/api/api.php";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_ptc= $pesetas['ptc_eur'];
$ptc= $euros/$valor_ptc;
$ptc= round($ptc, 2);
//precio en PesetaCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "ptc") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$ptc."</b> de Pesetacoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
NEW CODE:
//precio en ReecoreCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_reex= $pesetas['eur'];
$reex= $euros/$valor_reex;
$reex= round($reex, 2);
//precio en ReecoreCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "reex") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$reex."</b> de Reecorecoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
It's because the now Coingecko API return a nested JSON which is simply a JSON file with a fairly big portion of its values being other JSON objects.
Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.
Using Phrase, keys will be stored by separating levels with a dot.
The new API returns a nested JSON object, where you need two steps to access the desired value:
$valor_reex= $pesetas['reecore']['eur'];
You might want to use ready library for this. Like this one https://github.com/npabisz/coingecko-api.
Install via composer:
composer require npabisz/coingecko-api
And then get your reecore price by:
$client = new \CoinGecko\Client();
$data = $client->Simple->Price->get([
'ids' => 'reecore',
'vs_currencies' => 'eur',
]);
$reecorePrice = $data['reecore']['eur'] ?? null;
Related
I created a wordpress plugin to retrieve the information of a token on pancakeswap. I don't understand why it doesn't show me the data. if someone can look at my code and tell me what's wrong that will be super nice. thank you in advance.
<?php
/*
Plugin name: WP PancakeSwap
Description: Ce plugin nous permet de dialoguer avec l' api PancakeSwap
Author: Jean Philippe Faucon
Version : 1.0
*/
/* Copyright 2021 Jean Philippe Faucon (email : jpfaucon81#hotmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Utilisation de l'API Pancakeswap.
// https://github.com/pancakeswap/pancake-info-api/blob/develop/v2-documentation.md
// Source : https://api.pancakeswap.info/api/v2/tokens/0xdb72feadd4a0734d62fa5a078551986519dca19d
// 1 étape : récupérer les infos auprès de PancakeSwap
function _get_wp_pancakeswap_datas () {
$args = array (
'timeout' => 120,
'httpversion' => '1.1'
);
$url = "https://api.pancakeswap.info/api/v2/tokens/0xdb72feadd4a0734d62fa5a078551986519dca19d";
$call = wp_remote_get($url, $args);
$response = wp_remote_retrieve_body($call);
return $response;
}
// 2 étape : mettre en forme les données
add_shortcode('pancakeswap','output_pancakeswap');
function output_pancakeswap() {
$datas = _get_wp_pancakeswap_datas () ;
//Nom et prix du token
$output = 'Nom du token : '.$datas->name;
$output .= '<br>';
$output .= 'Valeur du token : '.$datas->price;
$output .= ' $';
$output .= '<br>';
$output .= 'Valeur du token en BNB : '.$datas->price_BNB;
return $output;
}
First of all you have to json decode the response.
If this function return the body json decoded as the name suggest wp_remote_retrieve_body($call);
try to "return $response->data" in the function _get_wp_pancakeswap_datas ()
{"updated_at":1636744974029,"data":{"name":"Alfcoin","symbol":"ALF","price":"0.1937757238779150782534763119032","price_BNB":"0.000314980409577114948657924847012"}}
If not you have to do something like this in the function _get_wp_pancakeswap_datas()
$response = json_decode(wp_remote_retrieve_body($call));
return $response->data;
This is essentially right out of the Wordpress manual.
You need to convert the json response to a php object.
You need to access the embedded object from the json response
Alternatively, you could opt for the json_decode() 2nd parameter that returns a php array instead of a php object.
function _get_wp_pancakeswap_datas () {
$args = array (
'timeout' => 120,
'httpversion' => '1.1'
);
$url = "https://api.pancakeswap.info/api/v2/tokens/0xdb72feadd4a0734d62fa5a078551986519dca19d";
$call = wp_remote_get($url, $args);
$response = json_decode(wp_remote_retrieve_body($call));
return $response;
}
add_shortcode('pancakeswap','output_pancakeswap');
function output_pancakeswap() {
$response = _get_wp_pancakeswap_datas();
//Nom et prix du token
$datas = $response->data;
$updateAt = $response->updated_at;
$output = 'Nom du token : '.$datas->name;
$output .= '<br>';
$output .= 'Valeur du token : '.$datas->price;
$output .= ' $';
$output .= '<br>';
$output .= 'Valeur du token en BNB : '.$datas->price_BNB;
return $output;
}
I'm making a sort of phone book and everything is fine:
Connection and authentification works perfectly
Research goes aswell
I can modify user's attributes
Then my boss asked me to add the Location attribute aka "Bureau" in french but openldap won't retrive it and only it.
Here's the code :
$attributes = array();
$attributes[] = 'givenname';
$attributes[] = 'sn';
$attributes[] = 'samaccountname';
$attributes[] = 'mail';
$attributes[] = 'telephonenumber';
$attributes[] = 'useraccountcontrol';
$attributes[] = 'dn';
$attributes[] = 'location';
/*------------------------------------------------------------------------------*/
if ($ldap_bind) // Si la connexon s'est effectuée
{
// Query sur LDAP
$resultat = ldap_search($ldap_connect, $dn, $search_filter, $attributes) or die('Une erreur est survenue pendant la recherche.');
// Transformation de l'objet LDAP en données explotables
$entries = ldap_get_entries($ldap_connect, $resultat);
But when I var_dump($entries), the location attribute isn't in the array, like if the name attribute was wrong. But according to msdn it's the right attribute correctly spelled.
So now I turn myself to you in hope someone can help on this issue.
In LDAP, if the attribute is not set, it will not be retrieved empty but will not be set in the response entry array.
Retrieve every attribute of the entry and var_dump it to see if it is set.
I try to get the image that is stored in a folder of my localhost, I do not understand what is the problem, the attribute in JSON IMAGEN get empty,
I need to convert it here..
<?php
/**
* Obtiene todas las metas de la base de datos
*/
const ESTADO = "estado";
const DATOS = "negocios";
const MENSAJE = "mensaje";
const CODIGO_EXITO = 1;
const CODIGO_FALLO = 2;
require '../data/Gastos.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
// Manejar petición GET
$negocios = Gastos::getAllNegocios();
//Definir el tipo de la respuesta
header('Content-Type: application/json');
$imagesPath = '/localhost:8888/htdocs/';
if ($negocios) {
$datos[ESTADO] = CODIGO_EXITO;
foreach($negocios as $meta) {
// Push an entry in the new array, replacing raw image with base64-encoded
$imgFileContents = file_get_contents($imagesPath.'/'.$meta['IMAGEN']);
$datos["negocios"][] = array(
'IDNEGOCIO' => $meta['IDNEGOCIO'],
'NOMBREIMAGEN' => $meta['NOMBREIMAGEN'],
'IMAGEN' => base64_encode($imgFileContents),
'NOMBRENEGOCIO' => $meta['NOMBRENEGOCIO'],
'DESCRIPCION' => $meta['DESCRIPCION'],
);
}
print json_encode($datos,JSON_UNESCAPED_UNICODE);
} else {
print json_encode(array(
ESTADO => CODIGO_FALLO,
MENSAJE => "Ha ocurrido un error"
));
}
}
?>
Get empty in JSON
{"estado":1,"negocios":[{"IDNEGOCIO":"1","NOMBREIMAGEN":"img_1","IMAGEN":"","NOMBRENEGOCIO":"YARYAS","DESCRIPCION":"Descripcion1"},{"IDNEGOCIO":"2","NOMBREIMAGEN":"img_2","IMAGEN":"","NOMBRENEGOCIO":"Skizza","DESCRIPCION":"Descripcion2"}]}
It is the directoy
I think it might be because you're $imagesPath URL is pointing to a directory incorrectly. In most localhost setups "htdocs" is already the default directory when travelling to the localhost server, so assuming its a relative URL it should be something like "http://localhost:8888/fotos/" not "http://localhost:8888/htdocs/fotos/".
Try:
$imagesPath = 'http://localhost:8888/';
I need to write a code that allows me to send an specific link within an array. This is a short idea of what I'm trying to do. Depending on the country code I'll send a brochure in the specific language. I also want to know if I can do it by switch...
This is the code I got so far...
<?php
$de_brochure = ('https://ruta/de-brochure.pdf');
$en_brochure = ('https://ruta/en-brochure.pdf');
$es_brochure = ('https://ruta/es-brochure.pdf');
$country_code = 'ES'; // Normally I get this code from a form.
$brochure = array ( $de_brochure, $en_brochure, $es_brochure );
$brochure_link = '';
if ( $country_code == 'ES' ) {
$to = 'info#kazzabe.com.es';
$subject = 'Ejemplo';
$txt = 'El dossier a enviar es' . $brochure_link[$brochure];
$headers = 'De: sample#sample.com' . '\r\n' .
'CC: anothersample#sample.com';
mail ($to, $subject, $txt, $headers );
} else {
echo $country_code . 'no es el código de españa';
}
When I run my code, this is the output I GET:
WARNING Illegal offset type on line number 17
NOTICE Uninitialized string offset: 1 on line number 17
You make your array and a unused "link" variable
$brochure = array ( $de_brochure, $en_brochure, $es_brochure );
$brochure_link = '';
And then access this link variable instead of the array:
$txt = 'El dossier a enviar es' . $brochure_link[$brochure];
^^^^^^^^^^^^^^^^^^^^^^^^^
This is where it fails. Using an array with named keys (a.k.a. hash) would make it easier:
$brochures = [
'DE' => 'https://ruta/de-brochure.pdf',
'EN' => 'https://ruta/en-brochure.pdf',
'ES' => 'https://ruta/es-brochure.pdf'
];
$country_code = 'ES';
# ...
$txt = 'El dossier a enviar es' . $brochures[$country_code];
do something like this
$brochure_link_arr= array(
"DE"=>'https://ruta/de-brochure.pdf',
"EN" =>'https://ruta/en-brochure.pdf',
"ES"=> 'https://ruta/es-brochure.pdf'
);
if ( $country_code == 'ES' ) {
..
$txt = 'El dossier a enviar es' . $brochure_link_arr[$country_code];
i'm struggling trying to remove the scaped characters from the json response in my CodeIgniter with PhilSturgeon REST Server.
Everything is working OK, but the problem comes with the response, when I access the URL to get the data in json format I get it, but with escaped characters.
Example:
http://localhost/revista_servidor/index.php/api/notas/nota/id/1
Gives me the next response:
[{"id":"1","autor":"Prueba autor","titulo":"Comprobaci\u00f3n de t\u00ed\u00edtulo.","subtitulo":"Comprobaci\u00f3n de subt\u00edtulo.","foto1":"http://link.a.foto/foto1","texto1":"Comprobaci\u00f3n de texto 1.\r\n","pauta1":"1","texto2":"Comprobaci\u00f3n de texto 2.\r\n","foto2":"http://link.a.foto/foto2","pauta2":"1","texto3":"Comprobaci\u00f3n de texto 3.","foto3":"http://link.a.foto/foto3","pauta3":"1","texto4":"Comprobaci\u00f3n de texto 4.","texto5":"Comprobaci\u00f3n de texto 5.","texto6":"Comprobaci\u00f3n de texto 6.","datosweb":"http://link.a.pagina.de.datos/","adelanto":"Comprobaci\u00f3n del texto de adelante","nrorevista":"69"}]
It escapes URLs adding a backslash \ and changing specials characters (ó in this example) with: \u00f3.
I've tried adding stripslashes()but didn't work.
I checked the response in developers tools and it comes as expected: Content-Type: application/json.
How can I fix this encoding problem? I've also checked the configuration files and there seems to be nothing to change for this issue.
I hope someone can point me in the right direction, below is my code:
Controller: /application/controllers/api/notas.php
function nota_get() {
// ID verification.
if ( !$this->get('id') ) {
// NO ID.
$this->response(NULL, 400);
}
$nota = $this->Notas_model->get( $this->get('id') );
if ($nota) {
stripcslashes($this->response($nota, 200));
}
else {
$this->response(NULL, 404);
}
}
Model: /application/models/notas_model.php
function get($id = 0) {
$this->load->database();
if ( $id ) {
$query = $this->db->get_where( 'notas', array('id' => $id) );
}
else {
$query = $this->db->get('notas');
}
return $query->result();
}
I don't know if this matters, but this data will be accessed via javascript in the client side.
Thanks in advance!
Its just the way JSON works, try json_decode function.
e.g:
$json = json_decode($json_string);
$json->autor;
1) You need to be using json_decode() and then urldecode(), instead of stripslashes()
2) Both urldecode() and stripslashes() take a string as an argument, while you are trying to feed into it an object -- which gets "autoreduced" into something that depends on the PHP version... Whatever it is, it's probably not what you are expecting.
In your code:
if ($nota) {
stripcslashes($this->response($nota, 200));
}
you'll need a) save the result of decoding to the same or another variable, b) to loop through your object ( $nota ) and unescape the value in each key-value pair.
Try
...
$cleanObject = array();
if ($nota) {
$decodedObject = json_decode($this->response($nota, 200));
foreach ( $decodedObject as $key => $value ) {
$cleanObject[$key] = urldecode( $value );
}
}
echo "<pre>";
print_r($cleanedObject);
echo "</pre>";
// output
/*
Array
(
[id] => 1
[autor] => Prueba autor
[titulo] => Comprobación de tíítulo.
[subtitulo] => Comprobación de subtítulo.
[foto1] => http://link.a.foto/foto1
[texto1] => Comprobación de texto 1.
[pauta1] => 1
[texto2] => Comprobación de texto 2.
[foto2] => http://link.a.foto/foto2
[pauta2] => 1
[texto3] => Comprobación de texto 3.
[foto3] => http://link.a.foto/foto3
[pauta3] => 1
[texto4] => Comprobación de texto 4.
[texto5] => Comprobación de texto 5.
[texto6] => Comprobación de texto 6.
[datosweb] => http://link.a.pagina.de.datos/
[adelanto] => Comprobación del texto de adelante
[nrorevista] => 69
)
*/
...
Hopefully, this is what you are looking to achieve.
Depending on your further needs, you may have to re-encode the result. Based on javascript you mention, you may then need to convert the result back to JSON:
$unescapedAndJSONencodedObject = json_encode( $cleanObject );