由于项目的需要,本人开始研究上传图片到素材库,于是实验成功,拿来分享下
直接看代码
//服务器入口地址
public function token(){
if(!isset($_GET["echostr"])){
$this->responseMsg();
}}
//这里通过关键词回复获取公众号发送的图片,这里可自由定义事件
public function responseMsg(){
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
//当回复公众号关键字时获取上传的图片素材
if($RX_TYPE=='text'){
$resultStr = $this->handleText($postObj);
echo $resultStr;
}
}
else {
echo "";
exit;}
}
//关键字方法
public function handleText($postObj)
{
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
//调用上传素材的方法$this->uploadImg()
$res=json_decode($this->uploadImg(),true);
//图片media_id$res['media_id']
$mediaid=$res['media_id'];
if(!empty($keyword )){
if($keyword){
$mediaid=$res['media_id'];
}
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $mediaid);
echo $resultStr;
}
}
//上传临时图片素材方法
function uploadImg(){
$filepath = __DIR__."/../../../public/b.jpg";
$url='https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$this->get_access_token().'&type=image';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//发送 POST 请求
curl_setopt($ch, CURLOPT_POST, true);
//全部数据使用HTTP协议中的 "POST" 操作来发送。
//$file_data = array('media' => '@'.$filepath);
//传递的数组,方式一:使用'@'符号加上文件的绝对路径来指引文件。这种方式适合PHP5.5之前的版本,
$file_data = array("media"=> new \CURLFile($filepath));
//传递的数组,方式二:从PHP5.5版本以后,引入了新的CURLFile 类来指向文件,参数传入的也是绝对路径
curl_setopt($ch, CURLOPT_POSTFIELDS, $file_data);
$res = curl_exec( $ch );
curl_close( $ch );
if($res){
//$res = json_decode($res,true);
return $res;
//返回的结果{"type":"image","media_id":"66daT1v5ucz0ucB6FFS683U6wrsod7SodtU21AthRRhWKpn4KFLDa9qjhOfSdhqg","created_at":1564885913}
}
}