<?php
class WeixinShare{
public function curlGet($url,$data){
$ch = curl_init();
// get的变量
$getData="";
foreach($data as $key=>$value){
$getData.="$key=$value&";
}
$getData=substr($getData,0,strlen($getData)-1);
$url.="?".$getData;
//设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//执行并获取HTML文档内容
$output = curl_exec($ch);
//释放curl句柄
curl_close($ch);
$output=json_decode($output,true);
return $output;
}
private function getAccesssToken($appId,$appSecret,$force=false){
$file=sys_get_temp_dir().'/access_token.json';
@$data=file_get_contents($file);
if($data) $data=json_decode($data,true);
$now=time();
if(!$data || $data['create_time']+$data['expire_time']<=$now || $force){
$url="https://api.weixin.qq.com/cgi-bin/token";
$data=array(
'grant_type'=>'client_credential',
'appid'=>$appId,
'secret'=>$appSecret,
);
$result=$this->curlGet($url,$data);
$data=array(
'access_token'=>$result['access_token'],
'expire_time'=>$result['expires_in']-1800,
'create_time'=>time(),
);
$data=json_encode($data);
file_put_contents($file,$data);
}
return $data['access_token'];
}
private function createRandomStr($length=16){
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
$strlen = 62;
while($length > $strlen){
$str .= $str;
$strlen += 62;
}
$str = str_shuffle($str);
return substr($str,0,$length);
}
public function configWeixin(){
$appId="APP_ID";
$appSecret="APP_SECERT";
$data=array();
$data['appId']=$appId;
$accessToken=$this->getAccesssToken($appId,$appSecret);
$params=array(
'access_token'=>$accessToken,
'type'=>'jsapi'
);
$result=$this->curlGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket",$params);
$jsapiTicket=$result['ticket'];
$nonceStr=$this->createRandomStr();
$timestamp=time();
$url=getgpc('shareUrl');
$string1=sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s",$jsapiTicket,$nonceStr,$timestamp,$url);
$data['signature']=sha1($string1);
$data['nonceStr']=$nonceStr;
$data['timestamp']=$timestamp;
$share=array(
'title'=>'分享标题',
'link'=>'分享链接',
'desc'=>'分享的文字说明',
'imgUrl'=>'分享图标的地址'
);
$data['share']=$share;
echo json_encode($data);
}
}