TP5-微信图片上传至服务器(干货)

如题:添加内容,pc点击获取二维码之后,用户扫码关注公众号,用户在公众号聊天界面发图,同步上传至pc页面, 代码如下:

//验证公众号
static $WX_TOKEN= '1bb16f6763a57-------77ef055adc';
//公众平台
private $WX_APPID="wx6aac0----c329c";
private $WX_SECRET="a5dea546d----------f4c20fa5aecd9";
//公众号对接
public function checkToken(){
$data=Request::instance()->get();
$echostr    = $data['echostr'];
$signature  = $data['signature'];
$timestamp  = $data['timestamp'];
$nonce      = $data['nonce'];
$signeSeed = [self::$WX_TOKEN, $timestamp, $nonce];
sort($signeSeed, SORT_STRING);
$signeStr = implode($signeSeed);
$signeHash = sha1($signeStr);
if( $signeHash == $signature && $echostr){
echo $echostr;
exit;
}else{
$this->responseMsg();
}
}
//返回信息
public function responseMsg(){
$postStr = file_get_contents("php://input");//访问请求的原始数据的只读流
if (!empty($postStr)){
//考虑到了安全问题。
libxml_disable_entity_loader(true);
//得到了数据之后,然后我们就是要解析微信服务器发送过来的xml数据包了
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
$fromruseropenid=trim($this->getUserInfo($postObj->FromUserName));
//            //关注之后利用二次opendi,获取用户信息
$userinfostr=json_decode($fromruseropenid,true);
switch ($RX_TYPE)
{
case "event":
$result = $this->receiveEvent($postObj,$userinfostr);
break;
case "text":
$result = $this->receiveText($postObj);
break;
case "image":
$result = $this->receiveImage($postObj,$userinfostr);
break;
case "location":
$result = $this->receiveLocation($postObj);
break;
case "voice":
$result = $this->receiveVoice($postObj);
break;
case "video":
$result = $this->receiveVideo($postObj);
break;
case "link":
$result = $this->receiveLink($postObj);
break;
default:
$result = "unknown msg type: ".$RX_TYPE;
break;
}
echo $result;
}else {
echo "false";
exit;
}
}
//接收事件消息
private function receiveEvent($object,$userinfostr='')
{
$content = "";
switch ($object->Event)
{
case "subscribe":
$content = "您好,很感谢您的关注!这里是咚咚租企业选址平台。\n我们将为您提供专业、高效、安心的选址服务!\n找办公室可以很简单!\n\n服务热线:400-8808-355\n咚咚租官网:www.dongdongzu.com";
break;
case "unsubscribe":
$content = "取消关注";
break;
case "SCAN":
if(empty($object->EventKey)){
$content = "二维码已失效,请刷新pc页面重新获取二维码重试";
}else{
if(empty($userinfostr)){
$content = "用户身份识别失败,请刷新pc页面重新获取二维码重试";
}else{
//获取用户id
$id = substr($object->EventKey,10,10);
//查询后台是否有绑定关系
$userinfo = db('admin')->where('id='.$id)->find();
//此一次绑定和重新绑定这个账号
if( $userinfo['wx_openid'] !== $userinfostr['openid'] ){
$update['wx_openid'] = $userinfostr['openid'];
$update['wx_info'] = json_encode($userinfostr);
db('admin')->where('id='.$id)->update($update);
}
}
}
$content = "HI,您已开启微信传图模式,点击左下的小键盘图标,发送你需要上传的图片吧。";
break;
//            case "CLICK":
//                switch ($object->EventKey)
//                {
//                    case "COMPANY":
//                        $content = "xx教育提供互联网相关产品与服务。";
//                        break;
//                    default:
//                        $content = "点击菜单:".$object->EventKey;
//                        break;
//                }
//                break;
case "LOCATION":
$content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
break;
case "VIEW":
$content = "跳转链接 ".$object->EventKey;
break;
default:
$content = "receive a new event: ".$object->Event;
break;
}
$result = $this->transmitText($object, $content);
return $result;
}
//接收图片消息
private function receiveImage($object,$userinfostr='')
{
$img_name = time().'_'.$object->MediaId;
$ls = ROOT_PATH.'public_old/'.$img_name.'.jpeg';
$oss_path = 'uploads/images/';
//上传至服务器
$getAccessToken = $this->getAccessToken();
$ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$getAccessToken}&media_id={$object->MediaId}");
$fp = fopen($ls, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$oss_url = upload_to_oss($oss_path.$object->MediaId.'.jpeg',$ls);
if(!empty($oss_url)){
$inset['wx_openid'] = $userinfostr['openid'];
$inset['wx_pic_url'] = $oss_url;
$inset['wx_times'] = time();
$inset['wx_pic_info'] = json_encode($object);
$inset['wx_user_info'] = json_encode($userinfostr);
$res = db('temporary')->insert($inset);
$content = '上传成功:'.$oss_url.'?x-oss-process=style/watermark';
@unlink($ls);
}else{
$content = '上传失败';
}
$result = $this->transmitText($object, $content);
return $result;
}
//回复文本消息
private function transmitText($object, $content)
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}
//关注之后返回用户的信息
public function getUserInfo($openid){
//获取token
$toen=$this->getAccessToken();
$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$toen&openid=$openid&lang=zh_CN";
$data=file_get_contents($url);
$user=json_decode($data,true);
$unionid=$user["openid"];
$urll="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$toen&openid=$unionid&lang=zh_CN";
//获取用户信息
$userifnfo=file_get_contents($urll);
return $userifnfo;
}
//获取access_token
private function getAccessToken(){
//        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->WX_APPID."&secret=".$this->WX_SECRET;
//        $retun = httpGet($url);
//        $retun = json_decode($retun,true);
//        return $retun;
$access_token = '';
//缓存access_token
if(file_exists(ROOT_PATH.'access_token.txt')){
$unsettime = filemtime (ROOT_PATH.'access_token.txt');
if($unsettime > time()+7000){
$access_token = file_get_contents (ROOT_PATH.'access_token.txt');
}
}
if(empty($access_token)){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->WX_APPID."&secret=".$this->WX_SECRET;
$retun = httpGet($url);
$retun = json_decode($retun,true);
$access_token = $retun['access_token'];
file_put_contents(ROOT_PATH.'access_token.txt',$access_token);
}
return $access_token;
}
public function GetWxQrcode(){
$user_id = $this->admin['id'];
$id = Request::instance()->param('id/d');
$access_token = '';
//缓存access_token
if(file_exists(ROOT_PATH.'access_token.txt')){
$unsettime = filemtime (ROOT_PATH.'access_token.txt');
if($unsettime > time()+7000){
$access_token = file_get_contents (ROOT_PATH.'access_token.txt');
}
}
if(empty($access_token)){
//加载小程序参数
require_once ROOT_PATH . 'extend/weapp/WeappApi.php';
//            $WeappApi =[
//                'appid' => config('weapp.appid'),
//                'appsecret' => config('weapp.appsecret')
//            ];
$WeappApi =[
'appid' => 'wx6a----b6c329c',
'appsecret' => 'a5dea546-----7daf4c20fa5aecd9'
];
if(empty($WeappApi['appid']) || empty($WeappApi['appsecret'])){
$this->result([], 0,'参数缺失');
}
$res = $this->getAccessToken($WeappApi);
$data = $res['access_token'];
file_put_contents(ROOT_PATH.'access_token.txt',$data);
$access_token = $res['access_token'];
}
$url['time'] = time(); //用户id -时间
$url['id'] = $url['time'].$user_id; //用户id -时间
$url['pic'] = $this->getQrcodeurl($access_token,$url['id'],2);
$url['user_id'] = $this->admin['id'];
$this->result($url,'1');
}
protected function getQrcodeurl($ACCESS_TOKEN,$fqid,$type = 1){
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$ACCESS_TOKEN;
if($type == 1){
//生成永久二维码
$qrcode= [
'action_name'=>'QR_LIMIT_SCENE',
'action_info'=>[
'scene'=>[
'scene_str'=>$fqid
]
]
];
//                '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_str": '.$fqid.'}}}';
}else{
//生成临时二维码
//            $qrcode = '{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str":"$fqid"}}}';
$qrcode= [
'expire_seconds'=>'604800',
'action_name'=>'QR_STR_SCENE',
'action_info'=>[
'scene'=>[
'scene_str'=>$fqid
]
]
];
}
$result = httpPost($url,json_encode($qrcode));
$oo = json_decode($result,true);
$url =  "https://mp.weixin.qq.com/cgi-bin/showqrcode?".'ticket='.$oo['ticket'].'';
return $url;
}
//获取access_token
private function getAccessToken($info=false){
if($info==false){ return false;  }
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$info['appid']."&secret=".$info['appsecret'];
$retun = httpGet($url);
$retun = json_decode($retun,true);
return $retun;
}
public function getimg(){
$post = Request::instance()->param();
$id = $post['id'] ? $post['id'] : $this->admin['id'];
$openid = $this->admin['wx_openid'] ? $this->admin['wx_openid'] : db('admin')->where("id=".$id)->find()['wx_openid'] ;
if(empty($openid)){
$this->result('请扫码先关注公众号','0');
}
$url = db('temporary')->where(" wx_openid = '".$openid."' and type = 0 ")->order('id asc')->find();
if($url==false){
$this->result('NO UPLOAD IMG','2');
}else{
$url['wx_pic_url']= $url['wx_pic_url'] ? $url['wx_pic_url'].'?x-oss-process=style/watermark' :'';
db('temporary')->where('id='.$url['id'])->update(['type'=>1]);
$this->result($url,1);
}
}

前台

setInterval( function(){
getimg()
} ,1000);
function getimg(){
$.post("{:url('room/getimg')}",{
// id:id,
// times:times
},function(res){
if(res.code==1){
var img_item = '<div class="upload_img_item">'+
'<img src="'+res.data.wx_pic_url+'" alt="">'+
'<input type="hidden" name="img[]" />'+
'<div class="item_action">'+
'  <div class="item_action_bg"></div>'+
'  <div class="item_action_content">'+
'    <a class="upload_img_list_one" onclick="upload_set_one_img(this)">设为封面</a>'+
'    <a class="upload_img_list_prev" onclick="upload_set_prev_img(this)"><</a>'+
'    <a class="upload_img_list_next" onclick="upload_set_next_img(this)">></a>'+
'    <a class="img_btn" onclick="upload_del_img(this)">x</a>'+
'  </div>'+
'</div>'+
'</div>';
$(".upload_img_list").append(img_item);
}
},'json')
}
<?php
namespace app\api\controller;
use \think\Request;
use \think\Db;
use \think\cache;
header("Content-type: text/html; charset=utf-8");
/*微信*/
class Wx extends \app\common\controller\ApiBase
{
static $WX_TOKEN= '1bb16f6763a5721942a54d77ef055adc';
//公众平台 测试
// private $WX_APPID="wx6aa42329c";
// private $WX_SECRET="a5de524a5aecd9";
// 正式
private $WX_APPID="wx4521fd68";
private $WX_SECRET="fd452979c";
public function checkToken(){
$data=Request::instance()->get();
$echostr    = $data['echostr'];
$signature  = $data['signature'];
$timestamp  = $data['timestamp'];
$nonce      = $data['nonce'];
$signeSeed = [self::$WX_TOKEN, $timestamp, $nonce];
sort($signeSeed, SORT_STRING);
$signeStr = implode($signeSeed);
$signeHash = sha1($signeStr);
if( $signeHash == $signature && $echostr){
file_put_contents (ROOT_PATH.'access_token_success.txt','1');
echo $echostr;
exit;
}else{
file_put_contents (ROOT_PATH.'access_token_error.txt',json_encode($this->responseMsg()));
$this->responseMsg();
}
}
//返回信息
public function responseMsg(){
$postStr = file_get_contents("php://input");//访问请求的原始数据的只读流
if (!empty($postStr)){
//考虑到了安全问题。
libxml_disable_entity_loader(true);
//得到了数据之后,然后我们就是要解析微信服务器发送过来的xml数据包了
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
$fromruseropenid=trim($this->getUserInfo($postObj->FromUserName));
//            //关注之后利用二次opendi,获取用户信息
$userinfostr=json_decode($fromruseropenid,true);
switch ($RX_TYPE)
{
case "event":
$result = $this->receiveEvent($postObj,$userinfostr);
break;
case "text":
$result = $this->receiveText($postObj);
break;
case "image":
$result = $this->receiveImage($postObj,$userinfostr);
break;
case "location":
$result = $this->receiveLocation($postObj);
break;
case "voice":
$result = $this->receiveVoice($postObj);
break;
case "video":
$result = $this->receiveVideo($postObj);
break;
case "link":
$result = $this->receiveLink($postObj);
break;
default:
$result = "unknown msg type: ".$RX_TYPE;
break;
}
echo $result;
}else {
echo "false";
exit;
}
}
//接收事件消息
private function receiveEvent($object,$userinfostr='')
{
$content = "";
switch ($object->Event)
{
case "subscribe":
$content = "您好,很感谢您的关注!这里是咚咚租企业选址平台。\n我们将为您提供专业、高效、安心的选址服务!\n找办公室可以很简单!\n\n服务热线:400-8808-355\n咚咚租官网:www.dongdongzu.com";
break;
case "unsubscribe":
$content = "取消关注";
break;
case "SCAN":
if(empty($object->EventKey)){
$content = "二维码已失效,请刷新pc页面重新获取二维码重试";
}else{
if(empty($userinfostr)){
$content = "用户身份识别失败,请刷新pc页面重新获取二维码重试";
}else{
//获取用户id
$id = substr($object->EventKey,10,10);
//查询后台是否有绑定关系
$userinfo = db('admin')->where('id='.$id)->find();
//此一次绑定和重新绑定这个账号
if( $userinfo['wx_openid'] !== $userinfostr['openid'] ){
$update['wx_openid'] = $userinfostr['openid'];
$update['wx_info'] = json_encode($userinfostr);
db('admin')->where('id='.$id)->update($update);
}
}
}
$content = "HI,您已开启微信传图模式,点击左下的小键盘图标,发送你需要上传的图片吧。";
break;
//            case "CLICK":
//                switch ($object->EventKey)
//                {
//                    case "COMPANY":
//                        $content = "xx教育提供互联网相关产品与服务。";
//                        break;
//                    default:
//                        $content = "点击菜单:".$object->EventKey;
//                        break;
//                }
//                break;
case "LOCATION":
$content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
break;
case "VIEW":
$content = "跳转链接 ".$object->EventKey;
break;
//            default:
//                $content = "receive a new event: ".$object->Event;
//                break;
}
$result = $this->transmitText($object, $content);
return $result;
}
//接收文本消息
private function receiveText($object)
{
switch ($object->Content)
{
case "文本":
$content = "这是个文本消息";
break;
case "你是?":
$content = "一个不愿透露名字的机器人,略略略";
break;
case "你好":
$content = "你好呀";
break;
case "图文":
case "单图文":
$content = array();
$content[] = array("Title"=>"咚咚组",  "Description"=>"官方网址点击查看", "PicUrl"=>"", "Url" =>"https://baidu.cn/");
break;
case "多图文":
$content = array();
$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
$content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
$content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
break;
case "音乐":
$content = array("Title"=>"大鱼", "Description"=>"歌手:周深", "MusicUrl"=>"http://fs.w.kugou.com/201806221135/3f0e5973d2cee2c083fd1d0a129921d3/G063/M08/05/11/H5QEAFc-bc6AfD3uAEycKVKAkaw783.mp3", "HQMusicUrl"=>"http://fs.w.kugou.com/201806221135/3f0e5973d2cee2c083fd1d0a129921d3/G063/M08/05/11/H5QEAFc-bc6AfD3uAEycKVKAkaw783.mp3");
break;
default:
$content = "咚咚组";
break;
}
if(is_array($content)){
if (isset($content[0]['PicUrl'])){
$result = $this->transmitNews($object, $content);
}else if (isset($content['MusicUrl'])){
$result = $this->transmitMusic($object, $content);
}
}else{
$result = $this->transmitText($object, $content);
}
return $result;
}
//接收图片消息
private function receiveImage($object,$userinfostr='')
{
$img_name = time().'_'.$object->MediaId;
$ls = ROOT_PATH.'public/temp/'.$img_name.'.jpeg';
$oss_path = 'uploads/images/';
//上传至服务器
$getAccessToken = $this->getAccessToken();
$ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$getAccessToken}&media_id={$object->MediaId}");
$fp = fopen($ls, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$oss_url = upload_to_oss($oss_path.$object->MediaId.'.jpeg',$ls);
if(!empty($oss_url)){
$inset['wx_openid'] = $userinfostr['openid'];
$inset['wx_pic_url'] = $oss_url;
$inset['wx_times'] = time();
$inset['wx_pic_info'] = json_encode($object);
$inset['wx_user_info'] = json_encode($userinfostr);
$res = db('temporary')->insert($inset);
$content = '上传成功:'.$oss_url.'?x-oss-process=style/watermark';
@unlink($ls);
}else{
$content = '上传失败';
}
$result = $this->transmitText($object, $content);
return $result;
}
//接收位置消息
private function receiveLocation($object)
{
$content = "你发送的是位置,纬度为:".$object->Location_X.";经度为:".$object->Location_Y.";缩放级别为:".$object->Scale.";位置为:".$object->Label;
$result = $this->transmitText($object, $content);
return $result;
}
//接收语音消息
private function receiveVoice($object)
{
if (isset($object->Recognition) && !empty($object->Recognition)){
$content = "你刚才说的是:".$object->Recognition;
$result = $this->transmitText($object, $content);
}else{
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitVoice($object, $content);
}
return $result;
}
//接收视频消息
private function receiveVideo($object)
{
$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
$result = $this->transmitVideo($object, $content);
return $result;
}
//接收链接消息
private function receiveLink($object)
{
$content = "你发送的是链接,标题为:".$object->Title.";内容为:".$object->Description.";链接地址为:".$object->Url;
$result = $this->transmitText($object, $content);
return $result;
}
//回复文本消息
private function transmitText($object, $content)
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}
//回复图片消息
private function transmitImage($object, $imageArray)
{
$itemTpl = "<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>";
$item_str = sprintf($itemTpl, $imageArray['MediaId']);
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复语音消息
private function transmitVoice($object, $voiceArray)
{
$itemTpl = "<Voice>
<MediaId><![CDATA[%s]]></MediaId>
</Voice>";
$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复视频消息
private function transmitVideo($object, $videoArray)
{
$itemTpl = "<Video>
<MediaId><![CDATA[%s]]></MediaId>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>";
$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA]></MsgType>
$item_str
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复图文消息
private function transmitNews($object, $newsArray)
{
if(!is_array($newsArray)){
return;
}
$itemTpl = "    <item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
";
$item_str = "";
foreach ($newsArray as $item){
$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
}
$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";
$result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
return $result;
}
//回复音乐消息
private function transmitMusic($object, $musicArray)
{
$itemTpl = "<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA]></MsgType>
$item_str
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//创建菜单 http://zhenfangapi.sz3.hostadm.net/wx/creatMenu
//https://api.dongdongzu.com/wx/creatMenu
public function creatMenu(){
//组装请求的url地址
$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->getAccessToken();
$data = array(
"button"=>array(
array(
'type'=>'view',
'name'=>'委托找房',
'url'=>'https://www.hxahr.cn'),
array('type'=>'view','name'=>'找办公室',"url"=> 'https://www.hxahr.cn'),
array('name'=>'更多','sub_button'=>array(
array(  'type'=>'view', 'name'=>'投放资源', 'url'=>'https://www.hxahr.cn'),
array(  'type'=>'view', 'name'=>'关于我们', 'url'=>'https://www.hxahr.cn'),
array(  'type'=>'view', 'name'=>'联系我们', 'url'=>'https://www.hxahr.cn'),
array(  'type'=>'view', 'name'=>'咚咚小程序', 'url'=>'https://www.hxahr.cn')
)),
)
);
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$result = httpPost($url,$data);
dump($result);
}
//获取自定义菜单
public function getMenu()
{
$url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->getAccessToken();
$result = httpGet($url);
var_dump($result);
}
// 删除自定义菜单
public function delMenu()
{
$url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$this->getAccessToken();
$result = httpGet($url);
dump($result);
}
//关注之后返回用户的信息
public function getUserInfo($openid){
//获取token
$toen=$this->getAccessToken();
$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$toen&openid=$openid&lang=zh_CN";
$data=file_get_contents($url);
$user=json_decode($data,true);
$unionid=$user["openid"];
$urll="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$toen&openid=$unionid&lang=zh_CN";
//获取用户信息
$userifnfo=file_get_contents($urll);
return $userifnfo;
}
//获取access_token
private function getAccessToken(){
//        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->WX_APPID."&secret=".$this->WX_SECRET;
//        $retun = httpGet($url);
//        $retun = json_decode($retun,true);
//        return $retun;
$access_token = '';
//缓存access_token
if(file_exists(ROOT_PATH.'access_token.txt')){
$unsettime = filemtime (ROOT_PATH.'access_token.txt');
if($unsettime > time()+7000){
$access_token = file_get_contents (ROOT_PATH.'access_token.txt');
}
}
if(empty($access_token)){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->WX_APPID."&secret=".$this->WX_SECRET;
$retun = httpGet($url);
$retun = json_decode($retun,true);
$access_token = $retun['access_token'];
file_put_contents(ROOT_PATH.'access_token.txt',$access_token);
}
return $access_token;
}
public function http_curl($url,$data =array(),$method ="get",$returnType ="json")
{
//1.开启会话
$ch = curl_init();
//2.设置参数
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
if($method!="get"){
curl_setopt($ch,CURLOPT_POST,TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
}
curl_setopt($ch,CURLOPT_URL,$url);
//执行会话
$json = curl_exec($ch);
curl_close($ch);
if($returnType == "json"){
return json_decode($json,true);
}
return $json;
}
}

点赞

发表评论