<?php
/**
* 微信父类控制器
* @author Songle
*
*/
namespace Home\Controller;
use Think\Controller;
class Wechat2Controller extends Controller
{
private $last_time = null;
private $appid = null;
private $appsecret = null;
public function __construct()
{
parent::__construct();
}
/**
* 添加微信分享接口
* 第一步:access token
*/
public function getAccessToken()
{
$appid = ‘wx55f7980035ddbc37‘; //获取用户唯一凭证
$secret = ‘b3a96346c6a10b97dfdc134d5f0dd506‘; //用户唯一凭证密钥
$time = time() + 7000; //当前时间+2小时等于过期时间
// 如果有未过期token
$map[‘expires‘] = array(‘gt‘, time());
$token = D(‘access_token‘)->order(‘id desc‘)->where($map)->getField(‘access_token‘);
if ($token) {
return $token;
} else {
$res = file_get_contents(‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=‘ . $appid . ‘&secret=‘ . $secret);
$res = json_decode($res, true);
$token = $res[‘access_token‘];
$model = D(‘access_token‘); //把获取的token存储到数据库中
if ($token) {
$data = array(
‘access_token‘ => $token,
‘expires_time‘ => $time,
);
$data = $model->add($data); //把获得的token存储到数据库中
}
return $token;
}
}
/**
* 添加微信分享接口
* 第二步:用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket
*/
public function getJsapiTicket()
{
$time = time() + 7000; //当前时间+2小时等于过期时间
$map[‘ticket_expires_time‘] = array(‘gt‘, time());
// 库里如果有未过期的 ticket
$res = D(‘access_token‘)->where($map)->field(‘ticket‘)->find();
if ($res) {
$ticket = $res[‘ticket‘];
$result[‘result‘] = $ticket;
return $result;
} else {
$token = $this->getAccessToken();
$res = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $token . "&type=jsapi");
$res = json_decode($res, true);
$ticket = $res[‘ticket‘];
// ticket不能频繁的访问接口来获取,在每次获取后,我们把它保存到数据库中。
$model = D(‘access_token‘); //把获取的ticket存储到数据库中
if ($ticket) {
$data = array(
‘access_token‘ => $token,
‘expires_time‘ => $time,
‘ticket‘ => $ticket,
‘ticket_expires_time‘ => $time,
);
$data = $model->where(array(‘access_token‘=>$token))->save($data); //把获得的token存储到数据库中
}
$result[‘result‘] = $ticket; //没查询到符合条件的
return $result;
}
}
}
原文地址:https://www.cnblogs.com/jamescr7/p/8978018.html