3,143
社区成员
发帖
与我相关
我的任务
分享
<?php
/**
* Created by PhpStorm.
* User: 11536
* Date: 2018/1/7
* Time: 16:15
*/
class WeChat{
private $_appid;
private $_appsecret;
private $_token;
public function __construct($_appid,$_appsecret,$_token)
{
$this->_appid=$_appid;
$this->_appsecret=$_appsecret;
$this->_token=$_token;
}
public function _request($curl,$https=true,$method='GET',$data=null){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$curl);
curl_setopt($ch,CURLOPT_HEADER,false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
if($https){
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
}
if($method=='POST'){
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
}
$content=curl_exec($ch);
curl_close($ch);
return $content;
}
public function _getAccessToken(){
$file='./accesstoken';
if(file_exists($file)){
$content=file_get_contents($file);
$content=json_decode($content);
if(time()-filemtime($file)<$content->expires_in){
return $content->access_token;
}
}
$curl='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_appid.'&secret='.$this->_appsecret;
//echo $this->_request($curl);
$content=$this->_request($curl);
file_put_contents($file,$content);
$content=json_decode($content);
return $content->access_token;
}
public function _getTicket($sceneid,$type='temp',$expire_seconds=604800){
if($type=='temp'){
$data='{"expire_seconds": %s, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
$data=sprintf($data,$expire_seconds,$sceneid);
}else{
$data='{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
$data=sprintf($data,$sceneid);
}
$curl='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->_getAccessToken();
$content=$this->_request($curl,true,'POST',$data);
$content=json_decode($content);
return $content->ticket;
}
public function _getQRcode($sceneid,$type='temp',$expire_seconds=604800){
$ticket=$this->_getTicket($sceneid,$type,$expire_seconds);
$ticket=urlencode($ticket);
$content='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket;
$qrcode=$this->_request($content);
return $qrcode;
}
}
$wechat=new WeChat('wx8e404573722b92f7','dea81a78de2d3f92f9fa965cd20cd9ec','');
//echo $wechat->_request('https://www.baidu.com');
//echo $wechat->_getAccessToken();
header('Content-type:image/jpeg');
echo $wechat->_getQRcode(30);