图书信息获取
上节通过微信扫码功能获取到了图书的ISBN信息,通过调用豆瓣提供的API可以很方便的获取到图书信息。调用方法很简单,只要调用https://api.douban.com//v2/book/isbn/isbn号,就可以获取到isbn对应的图书信息,具体说明可以参考豆瓣官方说明。
获取图书信息的主要代码:
class DouBanApi{
public function getDoubanInfo($isbn) {
$url = "https://api.douban.com//v2/book/isbn/";
$url .= $isbn; $content = file_get_contents($url);
$bookInfo = json_decode($content, true);
$img = $bookInfo["image"];
$bookInfo['image'] = substr($img, strrpos($img, '/') + 1);
$ret = $this->getImage($img, '', 1);
if ($ret == true) {
return $bookInfo;
} else {
return false;
}
}
}
在接收消息的处理函数中,在scancode_waitmsg消息处理中添加代码,
private function receiveEvent($object) {
$content = "";
switch ($object->Event) {
case "subscribe":
$content = "欢迎关注wxbook公众号!";
break;
case "unsubscribe":
$content = "谢谢关注wxbook公众号!";
break;
case "scancode_waitmsg":
$isbn = substr($object->ScanCodeInfo->ScanResult, 7);
$content = "isbn:" . $isbn;
$douBanObj = new DoubanApi();
$bookInfo = $douBanObj->getDoubanInfo($isbn);
$image = $bookInfo["images"]["large"];
if (is_array($bookInfo['author']) && sizeof($bookInfo['author']) > 0) {
$bookInfo['author'] = $bookInfo['author'][0];
} else {
$bookInfo['author'] = '';
}
$content = array();
$summary = mb_substr($bookInfo['summary'], 0, 200, 'utf-8') . '...';
$content[] = array( "Title" => "已成功添加:" . $bookInfo["title"], "Description" => $summary, "PicUrl" => $image, "Url" => $check_url, );
break;
default:
$content = "receive a new event: " . $object->Event;
break;
}
if (is_array($content)) {
if (isset($content[0]['PicUrl'])) {
$result = $this->transmitPicUrl($object, $content);
}
} else {
$result = $this->transmitText($object, $content);
}
return $result;
}
增加处理图片和url的函数。
private function transmitPicUrl($object, $arr_item, $funcFlag = 0)
{
$itemTpl = " <item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
";
$item_str = "";
foreach ($arr_item as $item) {
$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
}
#防止字符中有百分号
$new_item_str = str_replace("%", "%%", $item_str, $i);
$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$new_item_str</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";
$resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $funcFlag);
return $resultStr;
}
在微信测试公众号使用扫码功能扫描一本书的二维码后可以得到下面的展现效果。