素材包括上传的图片或图文,并将素材上传到公众号服务器上,首先要获取图片的URL,并将获取到的相对路径改为绝对路径,上传的图片可以使临时的也可以是永久的,由staus_type这个来判断,上传公众号服务器要获取access_token(在之前我已经封装好的一个函数中点击打开链接),然后在接入上传图片的接口,一个是临时素材的接口一个是永久素材的接口,再根据得到的media_id将数据存入,具体代码如下:
//图片上传公众号服务器
public function image_submit(){
$url=I('post.url');//图片在本地服务器上的路径
//相对路径->绝对路径
$file=realpath('.'.$url);
// echo $file;
// exit;
$staus_type=I('post.staus_type');//临时,永久
$accessToken=getAccess_token();
include APP_PATH . 'LaneWeChat/lanewechat.php';
if($staus_type==0){
//临时素材
$api="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$accessToken&type=image";
}else{
//永久素材
$api="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=$accessToken&type=image";
}
$data['media']=Curl::addFile($file);
$ret=Curl::callWebServer($api,$data,'post',true,false);
if (isset($ret['media_id'])) {
$mp=$this->mp;
$data['mp_id']=$mp['id'];
$data['type']='image';
$data['url']=$url;
$data['media_id']=$ret['media_id'];
$data['create_time']=time();
M('material')->add($data);
$this->ajaxReturn(array('msg'=>"上传成功!"));
} else {
$this->ajaxReturn(array('msg'=>$ret));
}
}
关于图文的管理,与图片是相似的,这时调用的则是图文的接口,一般图文中的图片是永久的接口,
具体代码如下:
//图文上传公众号服务器
public function news_submit(){
$url=I('post.url');//图片在本地服务器上的路径
//相对路径->绝对路径
$file=realpath('.'.$url);
$title=I('post.title');
$content=I('post.content');
$link=I('post.link');
$accessToken=getAccess_token();
include APP_PATH . 'LaneWeChat/lanewechat.php';
//上传永久图片api
$api="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=$accessToken&type=image";
$data['media']=Curl::addFile($file);
$ret=Curl::callWebServer($api,$data,'post',true,false);
if (isset($ret['media_id'])) {
$arr=array(
'title'=>$title,
'thumb_media_id'=>$ret['media_id'],
'author'=>'ssh',
'digest'=>'aaa',
'show_cover_pic'=>1,
'content'=>$content,
'content_source_url'=>$link
);
$data['articles'][]=$arr;
$data=json_encode($data,JSON_UNESCAPED_UNICODE);
$api="https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=$accessToken";
$ret=Curl::callWebServer($api,$data,'post',true,false);
if (isset($ret['media_id'])) {
$mp=$this->mp;
$arr['mp_id']=$mp['id'];
$arr['title']=$title;
$arr['url']=$url;
$arr['link']=$link;
$arr['content']=$content;
$arr['create_time']=time();
M('material')->add($arr);
$this->ajaxReturn(array('msg'=>"上传成功!"));
}
else {
$this->ajaxReturn(array('msg'=>$ret));
// $this->ajaxReturn($ret);
}
}else{
$this->ajaxReturn($ret);
}
}
关于图片上传的方法
点击打开链接