如何修复WordPress PancakeSwap插件无法展示代币数据的问题
问题排查及修复代码
你的插件无法正常输出数据有三个核心问题:
- 接口返回的是JSON格式字符串,你没有执行解码操作就直接当作对象读取属性,属于基础类型错误
- PancakeSwap v2 代币接口的返回结果外层嵌套了
data字段,不能直接在返回结果顶层读取name、price等属性 - 缺少请求失败、数据异常的容错逻辑,异常场景下会直接抛出PHP错误
修正后的完整代码如下:
<?php /* Plugin name: WP PancakeSwap Description: 该插件用于对接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 */ // 从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); // 判断请求是否出错 if (is_wp_error($call)) { return false; } $response = wp_remote_retrieve_body($call); $decode_data = json_decode($response); // 判断JSON解码是否成功,以及是否存在data字段 if (json_last_error() !== JSON_ERROR_NONE || !isset($decode_data->data)) { return false; } return $decode_data->data; } // 注册短代码 add_shortcode('pancakeswap','output_pancakeswap'); function output_pancakeswap() { $datas = _get_wp_pancakeswap_datas(); // 数据异常时的提示 if (!$datas) { return '代币信息获取失败,请稍后重试'; } $output = '代币名称:'.$datas->name; $output .= '<br>'; $output .= '代币价格:'.$datas->price; $output .= ' $'; $output .= '<br>'; $output .= '代币BNB计价:'.$datas->price_BNB; return $output; }
部署后直接在文章/页面中插入[pancakeswap]短代码即可正常展示数据。
内容的提问来源于stack exchange,提问作者kehops81
相关产品推荐
相关产品推荐

