<?php
header('Content-type:text');
define("TOKEN", "jiesen365");
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
}else{
$wechatObj->valid();
}
class wechatCallbackapiTest
{
static $qrcodeid = '';
//验证签名
public function valid()
{
$echoStr = $_GET["echostr"];
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if ($tmpStr == $signature) {
echo $echoStr;
exit;
}
}
//响应消息
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)) {
$this->logger("R \r\n" . $postStr);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
$form = trim($postObj->FromUserName); //$object->FromUserName, $object->ToUserName, time());
$to = trim($postObj->ToUserName);
$datas = trim($postObj->Content);
$xml = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$imageurl = "yjH_kDDMGcWnWzuW_aG0Dqc9P5aNf2jHZfV4r3pSLUET8-jHmVOkBNr_FpgcOxvT";
// $imageurl = $postObj->MediaId;
$xml_pic = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
if (strstr($datas, '1')) {
$this->get_qrcode($form); //获取二维码
// $this->get_user_info($form); //获取用户信息(头像、姓名、性别)
// $this->get_userid($form); //获取用户userid
$result = sprintf($xml_pic, $form, $to, time(), $this->qrcodeid);
$this->logger("T \r\n" . $result);
echo $result;
}else if($RX_TYPE == 'event'){
}else{
$this->get_user_info($form);
$result = sprintf($xml, $form, $to, time(), "你好呀~");
$this->logger("T \r\n" . $result);
echo $result;
}
}else {
echo "";
exit;
}
}
//从系统中获取用户userid
public function get_userid($openid){
define('PHPCMS_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
include PHPCMS_PATH.'/../phpcms/base.php';
$third_party = pc_base::load_model('third_party_model');
$wfinfo = $third_party->get_one(array('wid'=>$openid),'userid');
file_put_contents('userid.txt',$openid.'+++'.$wfinfo[userid]);
}
//获取二维码
public function get_qrcode($form){
$appid = "wxbbae0ae85ac85399";
$appsecret = "7252f9a7d06601e6f57d7378b36672f2";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$output = $this->https_request($url);
$jsoninfo = json_decode($output, true);
$access_token = $jsoninfo["access_token"];
//------------以上为获取access_token----------------
$qrcode = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 10000}}}';
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";
$result = $this->https_request($url,$qrcode);
$jsoninfo = json_decode($result,true);
$ticket = $jsoninfo['ticket']; //获取到了ticket
//通过ticket换取二维码
$ticket=urlencode($ticket);
$url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$ticket}";
// $file= file_put_contents('qrcode.txt',$url);
$this->addwater($form,$url,$access_token);
}
//下载临时二维码图片到本地并将其以水印形式加到背景图片上
public function addwater($form,$url,$access_token){
$filename=$form.'.jpg';
$imageInfo=$this->downLoadImage($url);
$local_file=fopen($filename,'w');
if(false !==$local_file){
if(false!==fwrite($local_file,$imageInfo['body'])){ //生成了二维码以openid为文件名保存在当前目录下
fclose($local_file);
}
}
$im=imagecreatefromjpeg($filename); //文件或url创建一个新图像,创建文件句柄返回提供使用
$maxwidth=180;
$maxheight=200;
$name='thumb_'.$form;
$filetype='.jpg';
$filename_thumb = $this->resizeImage($im,$maxwidth,$maxheight,$name,$filetype);//将图片进行等比缩放
$dst_path='dst.png';//目标图片(背景图片)
$src_path=$filename_thumb;//水印图片(二维码)
$new_path='qrcode/'.$form;//专属海报(最后生成的图片)
$this->addWM($dst_path,$src_path,$new_path,$left=280,$top=820); //将二维码已水印形式加到图片上
@unlink($filename);
@unlink($filename_thumb);
$this->addpic($form,$access_token);
}
public function addpic($form,$access_token){
//下载头像图片到本地并以水印形式加到背景图片上
$filename="photo_".$form.".jpg";
$user_photo = $this->get_user_info($form);
$imageInfo=$this->downLoadImage($user_photo['headimgurl']);
$local_file=fopen($filename,'w');
if(false !==$local_file){
if(false!==fwrite($local_file,$imageInfo['body'])){
fclose($local_file);
}
}
$im=imagecreatefromjpeg($filename);
$maxwidth=150;
$maxheight=150;
$name='thumb_photo_'.$form;
$filetype='.png';
$filename_thumb = $this->resizeImage($im,$maxwidth,$maxheight,$name,$filetype);
$dst_path='qrcode/'.$form.'.png';//目标图片
$src_path=$filename_thumb;//水印图片
$new_path='qrcode/'.$form;//专属海报
$this->addWM($dst_path,$src_path,$new_path,$left=85,$top=710);
@unlink($filename);
@unlink($filename_thumb);
//以下为上传临时素材(上传生成的二维码成临时素材)
$url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=image";
$josn = array('media' => '@' . realpath($dst_path));
$res = $this->curl_post($url,$josn);
//file_put_contents('upload_qrcode.txt',$res);
$this->qrcodeid = $res; //返回给用户二维码的素材id
}
//获取用户信息(姓名、性别、头像...)
public function get_user_info($openid){
$appid = "wxbbae0ae85ac85399";
$appsecret = "7252f9a7d06601e6f57d7378b36672f2";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$output = $this->https_request($url);
$jsoninfo = json_decode($output, true);
$access_token = $jsoninfo["access_token"];
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
$output = $this->https_request($url);
// file_put_contents('user_info.txt',$output); //用json信息
return json_decode($output,true);
}
public function https_request($url,$data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
//下载生成的二维码图片到本地
function downLoadImage($url){
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_NOBODY,0);//只取body头
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$package=curl_exec($ch);
$httpinfo=curl_getinfo($ch);
curl_close($ch);
return array_merge(array('body'=>$package),array('header'=>$httpinfo));
}
//将图片进行等比缩放
function resizeImage($im,$maxwidth,$maxheight,$name,$filetype)
{
$pic_width = imagesx($im);
$pic_height = imagesy($im);
if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
{
if($maxwidth && $pic_width>$maxwidth)
{
$widthratio = $maxwidth/$pic_width;
$resizewidth_tag = true;
}
if($maxheight && $pic_height>$maxheight)
{
$heightratio = $maxheight/$pic_height;
$resizeheight_tag = true;
}
if($resizewidth_tag && $resizeheight_tag)
{
if($widthratio<$heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
}
if($resizewidth_tag && !$resizeheight_tag)
$ratio = $widthratio;
if($resizeheight_tag && !$resizewidth_tag)
$ratio = $heightratio;
$newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio;
if(function_exists("imagecopyresampled"))
{
$newim = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
}
else
{
$newim = imagecreate($newwidth,$newheight);
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
}
$name = $name.$filetype;
imagejpeg($newim,$name);
imagedestroy($newim);
}
else
{
$name = $name.$filetype;
imagejpeg($im,$name);
}
return $name;
}
//将二维码以水印方式加到背景图片上
function addWM($dst_path,$src_path,$new_path,$left='',$top='')
{
$dst = imagecreatefromstring(file_get_contents($dst_path));
$src = imagecreatefromstring(file_get_contents($src_path));
if(!$left){
$left=50;
}
if(!$top){
$top=50;
}
//获取水印图片的宽高
list($src_w, $src_h) = getimagesize($src_path);
//将水印图片复制到目标图片上,最后个参数50是设置透明度,这里实现半透明效果
// imagecopymerge($dst, $src, 10, 10, 0, 0, $src_w, $src_h, 50);
//直接将水印图片加到目标图片上
imagecopy($dst, $src, $left, $top, 0, 0, $src_w, $src_h);
//有header输出图片,无header保存图片
list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
switch ($dst_type){
case 1://GIF
// header('Content-Type: image/gif');
imagegif($dst,$new_path.".gif");
break;
case 2://JPG
// header('Content-Type: image/jpeg');
imagejpeg($dst,$new_path.".jpg");
break;
case 3://PNG
// header('Content-Type: image/png');
imagepng($dst,$new_path.".png");
break;
default:
break;
}
imagedestroy($dst);
imagedestroy($src);
}
//curl实现post请求
function curl_post($url, $data = null)
{
//创建一个新cURL资源
$curl = curl_init();
//设置URL和相应的选项
curl_setopt($curl, CURLOPT_URL, $url);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//执行curl,抓取URL并把它传递给浏览器
$output = curl_exec($curl);
//关闭cURL资源,并且释放系统资源
curl_close($curl);
$output = json_decode($output,true);
return $output['media_id'];
}
//日志记录
private function logger($log_content)
{
if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
$max_size = 1000000;
$log_filename = "log.xml";
if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
}
}
}
?>