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']);
}
}
~~~
其中相關內容

在微信web開發工具中運行該方法

測試生成的短連接與放入的長連接頁面一致
本節源碼下載(下載密碼:vif1)
[源碼下載](https://pan.baidu.com/s/1rbBb1T3AX2vv1FVUyC84fQ)