/**标签:ch,微信,H5,access,token,data,curl,PHP,config From: https://www.cnblogs.com/zhengkk/p/17096014.html
* 功能:获取小程序access_token
* Author:郑康凯
* Date: 2023/2/6 0006 15:14
*/
public function hhsGetAccessToken()
{
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$SCHOOL_HOST=CD('SCHOOL_HOST');
//if($_SERVER['SERVER_NAME']==$SCHOOL_HOST){
if(1){
$where['config_name'] = array('eq', 'H_Access_Token');
$access_token_info = M('config')->where($where)->find();
$thetime = $access_token_info['config_time'] + 7000;
if ($thetime < time() || empty($access_token_info['config_value'])) {
//获取小程序access_token方法
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . CD('H_AppID') . "&secret=" . CD('H_AppSecret');
$res = json_decode(httpPost($url));
$access_token = $res->access_token;
// 保存tocken
$data['config_value'] = $access_token;
$data['config_time'] = time();
if (empty($access_token_info)) {
$data['config_name'] = 'H_Access_Token';
M('config')->add($data);
} else {
M('config')->where($where)->save($data);
}
return $access_token;
} else {
return $access_token_info['config_value'];
}
}else{
return false;
}
}
//获取小程序生成短链
public function getUrlLInk(){
$url = 'https://api.weixin.qq.com/wxa/generate_urllink?access_token='.$this->hhsGetAccessToken();
$data='{"path": "/pages/tabbars/main/main","query": "","is_expire":true,"expire_type":0,"expire_interval":1,"env_version": "release"} ';
$res = json_decode($this->httpPost($url,true,'POST',$data),true);
$href_url=$res['url_link'];
Header("HTTP/1.1 303 See Other");
Header("Location:$href_url ");
exit;
}
/**
* 发送httpPost
* @param $curl
* @param bool $https
* @param string $method
* @param null $data
* @return mixed
*/
function httpPost($curl, $https = true, $method = 'GET', $data = null)
{
$ch = curl_init(); // 初始化curl
curl_setopt($ch, CURLOPT_URL, $curl); //设置访问的 URL
curl_setopt($ch, CURLOPT_HEADER, false); //放弃 URL 的头信息
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //请求时间限制(s)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而不直接输出
if ($https) { //判断是否是使用 https 协议
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服务器的验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //做服务器的证书验证
}
if ($method == 'POST') { //是否是 POST 请求
curl_setopt($ch, CURLOPT_POST, true); //设置为 POST 请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST的请求数据
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'Content-Type:application/json'
));
}
$content = curl_exec($ch); //开始访问指定URL
$request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
curl_close($ch); //关闭 cURL 释放资源
return $content;
}