1.在根目录下的/Application/Home/Controller文件夹中的UrlController.class.php文件,书写相关方法
~~~
<?php
namespace Home\Controller;
use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;
class UrlController extends Controller
{
private $appid="wx165112bf167af76c";
private $appSecret="c65b22bfcf03fdd98504eac299701b03";
private $WechatAuth="";//初始化WechatAuth类
private $access_token="";//缓存token
public function __construct(){
parent::__construct();//可能内部已经有这个构造方法了,因此加上这个
if(!session('token')){
$this->WechatAuth=new WechatAuth($this->appid,$this->appSecret);//初始化WechatAuth类
$WechatAuth=$this->WechatAuth;
$token=$WechatAuth->getAccessToken();
session(array('expire'=>$token['expires_in']));//设置过期时间
session('token',$token['access_token']);//缓存token
$this->access_token=$token;
}else{
$token=session('token');
$this->WechatAuth=new WechatAuth($this->appid,$this->appSecret,$token);//初始化WechatAuth类
$this->access_token=$token;//缓存token
}
}
//生成带参数的二维码
public function createCode(){
header('Content-type:text/html;charset=utf-8;');
$WechatAuth=$this->WechatAuth;
$ticket=$WechatAuth->qrcodeCreate('10086');
//var_dump($ticket);
//$src=$WechatAuth->showqrcode($ticket['ticket']);//将获取地址放入浏览器中可以直接获得二维码
//var_dump($src);
echo "<img width='70%' src='https://mp.weixin.qq.com/cgi-bin/showqrcode?
ticket=gQEi8jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyaEhhdW9RSmdmYjAxMDAwMG
cwMzAAAgSVn59aAwQAAAAA'>";
}
//长连接转短连接
public function short(){
$WechatAuth=$this->WechatAuth;
$data=$WechatAuth->shorturl("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=99909276_hao_pg&wd=%E4%BA%8C%E7%BB%B4%E7%A0%81%20site%3Aweixin.qq.com&oq=%25E4%25BA%258C%25E7%25BB%25B4%25E7%25A0%2581%2520site%253Aweixin.qq.com&rsv_pq=aec782970000593c&rsv_t=3ba1NEgMEGYo0PYSwtv1CsstkUiXpg2Nw9NxRXW8eCwrKaXbIl9A8I4CLB2AmnZOxdbYpMNi&rqlang=cn&rsv_enter=0");
var_dump($data['short_url']);
}
}
~~~
其中相关内容
![](https://box.kancloud.cn/2f49598a8b8c1ba047e7866e8c9b286c_848x241.png)
在微信web开发工具中运行该方法
![](https://box.kancloud.cn/dfcfb5a5719c44b3e95a2b611bbea3b7_965x416.png)
测试生成的短连接与放入的长连接页面一致
本节源码下载(下载密码:vif1)
[源码下载](https://pan.baidu.com/s/1rbBb1T3AX2vv1FVUyC84fQ)