新浪微博API生成短连接

经过新浪微博API,生成短连接,支持一次性转多个长连接

什么是短连接

短连接,通俗来讲,就是将长的URL网址,经过程序计算等方式,转换为简短的网址字符串。

短连接服务

国内各大微博都推出了本身的短连接服务。例如新浪微博、腾讯微博等。php

为何选用新浪微博API

  1. 新浪微博短连接API是开放的
  2. 新浪微博短连接API不须要用户登陆

文档查询连接

使用方法

拿到本身的AppKey后,替换类的成员属性$appKey的值便可,以下这样的,$shortUrl是API请求地址html

// APPkey,我在网上找的(https://fengmk2.com/blog/appkey.html),能够本身申请
protected $appKey = '569452181';
// 转短链接API地址
protected $shortUrl = 'https://api.weibo.com/2/short_url/shorten.json?';复制代码

其余的,基本不须要配置,直接实例化类ShortLink,而后调用方法getShortUrl便可,须要说明的是长连接URL数组$longUrl里的值能够传多个值json

固然了,为了方便,我写为一个类,能够根据本身的须要,进行调整,知足本身的需求便可。api

源码

<?php /** * 经过新浪微博API,生成短连接,支持一次性转多个长连接 * Class shortClass * @time 2018-08-14 * @author gxcuizy */ Class ShortLink { // APPkey,我在网上找的(https://fengmk2.com/blog/appkey.html),能够本身申请 protected $appKey = '569452181'; // 转短链接API地址 protected $shortUrl = 'https://api.weibo.com/2/short_url/shorten.json?'; /** * 生成短连接 * @param array $longUrl 长连接数组 * @return array 返回短链接数据 */ public function getShortUrl($longUrl = []) { $code = true; $msg = '请求成功!'; $result = []; // 长连接数组为空,不处理 if (empty($longUrl)) { $code = false; $msg = '长连接数据不能为空'; return ['code' => $code, 'msg' => $msg, 'result' => $result]; } // 拼接请求URL $longUrlStr = $this->_getLongUrl($longUrl); $shortUrl = $this->shortUrl; $appKey = $this->appKey; $param = 'source=' . $appKey . '&' . $longUrlStr; $curlUrl = $shortUrl . $param; // 发送CURL请求 $result = $this->_sendCurl($curlUrl); return ['code' => $code, 'msg' => $msg, 'result' => $result]; } /** * 获取请求URL字符串 * @param array $longUrl 长连接数组 * @return string 长连接URL字符串 */ private function _getLongUrl($longUrl = []) { $str = ''; foreach ($longUrl as $url) { $str .= ('url_long=' . $url . '&'); } $newStr = substr($str, 0, strlen($str) - 1); return $newStr; } /** * 发送CURL请求(GET) * @param string $curlUrl 请求地址 * @return array 返回信息 */ private function _sendCurl($curlUrl) { // 初始化 $ch = curl_init(); // 设置选项,包括URL curl_setopt($ch, CURLOPT_URL, $curlUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // 执行并获取HTML文档内容 $output = curl_exec($ch); // 释放curl句柄 curl_close($ch); // Json数据转为数组 $result = json_decode($output, true); return $result; } } // 实例化对象 $shortObj = new ShortLink(); // 多个链接能够直接放到数组中,相似$longUrl = ['url1', 'url2', ……] $longUrl = ['http://blog.y0701.com/index.html']; // 开始转长连接为短连接 $result = $shortObj->getShortUrl($longUrl); print_r($result);复制代码

结束语

上面说到的网上查找获得的一些AppKey,由于来源不明,因此,不建议用于生产环境,须要用于生产环境的话,建议直接在新浪微博开发者平台里建立本身的应用就行。数组

相关文章
相关标签/搜索