<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use think\Loader;
class Shar extends Base{
private $appid = 'xxxxxx';
private $secret = 'xxxxxx';
public function get_access_token(){
$token = Db::table('token')->where('id',1)->find();
if($token){
if($token['over_time']<time()){
$data = $this->access_token();
Db::table('token')->where('id',1)->update(['type'=>$data['access_token'],'over_time'=>intval(time())+intval($data['expires_in'])-20]);
}else{
$data['access_token'] = $token['type'];
}
}else{
$data = $this->access_token();
Db::table('token')->insert(['id'=>1,'type'=>$data['access_token'],'over_time'=>intval(time())+intval($data['expires_in'])-20]);
}
return $data['access_token'];
}
public function access_token(){
$appid = $this->appid;
$secret = $this->secret;
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
$user = json_decode(file_get_contents($url));
if (isset($user->errcode)) {
echo 'error:' . $user->errcode.'<hr>msg :' . $user->errmsg;exit;
}
$data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
return $data;
}
//获取jsapi_ticket
public function get_jsapi_ticket(){
$jsapi_ticket = Db::table('token')->where('id',2)->find();
if($jsapi_ticket){
if($jsapi_ticket['over_time']<time()){
$data = json_decode($this->jsapi_ticket($this->get_access_token()),true);
Db::table('token')->where('id',2)->update(['type'=>$data['ticket'],'over_time'=>intval(time())+intval($data['expires_in'])-20]);
}else{
$data['ticket'] = $jsapi_ticket['type'];
}
}else{
$data = json_decode($this->jsapi_ticket($this->get_access_token()),true);
Db::table('token')->insert(['id'=>2,'type'=>$data['ticket'],'over_time'=>intval(time())+intval($data['expires_in'])-20]);
}
return $data['ticket'];
}
public function jsapi_ticket($access_token){
$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
$user = file_get_contents($url);
if (isset($user->errcode)) {
echo 'error:' . $user->errcode.'<hr>msg :' . $user->errmsg;exit;
}
$data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
return $data;
}
//获取签名
public function sing(){
$url = request()->param('url');
$data['noncestr'] = $this->nonce_str();
$data['jsapi_ticket'] = $this->get_jsapi_ticket();
$data['timestamp'] = time();
$data['url'] = $url;
ksort($data);
$stringA = '';
foreach ($data as $key=>$value){
if(!$value) continue;
if($stringA) $stringA .= '&'.$key."=".$value;
else $stringA = $key."=".$value;
}
$newdata['signature'] = sha1($stringA);
$newdata['nonceStr'] = $data['noncestr'];
$newdata['timestamp'] = $data['timestamp'];
return $newdata;
}
//随机字符串算法
private function nonce_str(){
$result = '';
$str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
for ($i=0;$i<32;$i++){
$result .= $str[rand(0,48)];
}
return $result;
}
}
?>