写了一天,掉了好多坑,不过还是写出来了
问题总结下:
1、php版本问题
2、微信上传图片路径问题
3、同步内容到素材库的array问题
//Author: echo <814683619@qq.com>
function _initialize()
{
$appid = 'wx********';
$secrect = '82ff*********************';
$this->accessTokens = $this->getToken($appid,$secrect);
parent::_initialize();
}
/**
*执行这个方法 通过id获取一篇文章到微信素材里面
*/
public function getWxarticle(){
$id=intval($this->_get('id'));
if($id){
$article=M('article')->where('id='.$id)->find();
//1、上传缩略图到微信服务器
if(!$article['thumb']){
$article['thumb']=$_SERVER['DOCUMENT_ROOT']."/nopic.jpg";
}
$thumb=$this->down_image($article['thumb']);
$thumb_url="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$this->accessTokens}&type=image";
$thumb_data = array('media' => new \CURLFile($thumb));
//php5.5以下版本需要这样写
//$thumb_data = array('media' => '@'.$thumb);
$thumb_result = $this->request_post($thumb_url,$thumb_data);
$thumb_result = json_decode($thumb_result, true); //返回微信media_id
//2、获取内容中的图片为数组,并替换正文图片为微信图
$pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$article['content'],$mat);
//dump($mat[1]); 获取图片数组
$img_url="https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={$this->accessTokens}";
foreach($mat[1] as $k=>$v){
//循环上传图片到微信服务器 并替换文章内容
$down_img[$k]=$this->down_image($v);
$data_imgs = array('media' => new \CURLFile($down_img[$k]));
//php5.5以下版本需要这样写
//$data_imgs = array('media' => '@'.$down_img[$k]);
$result = $this->request_post($img_url,$data_imgs);
$wxresult = json_decode($result, true);
$article['content']=str_replace($v,$wxresult['url'],$article['content']);
}
//3、上传到微信公众号素材里
$article_url="https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={$this->accessTokens}";
//这里的参数
$jsonArr=array(
'articles'=>array(
array(//很多人没注意这个少了这层array 会报 44003 empty news data 错误
'title'=>$article['title'],
'thumb_media_id'=>$thumb_result['media_id'],
'author'=>$article['author'],
'show_cover_pic'=>1,
'content'=>$article['content'],
'content_source_url'=>'http://m.domain.com'.$article['url'],
'need_open_comment'=>1,
'only_fans_can_comment'=>0,
),
/*
** 如果要加一组的完善这个就oK,这里不演示
array(
'title'=>'标题2',
'thumb_media_id'=>'填写素材id',
'author'=>'author',
'show_cover_pic'=>0,
'content'=>'content',
'content_source_url'=>'http://m.baidu.com',
'need_open_comment'=>1,
'only_fans_can_comment'=>0,
)
*/
),
);
$data_article=json_encode($jsonArr,JSON_UNESCAPED_UNICODE);
$result_article = $this->request_post($article_url,$data_article);
$result_end = json_decode($result_article, true);
if($result_end['media_id']){
echo '['.$article['title'].']传输成功 ^_^【】';
}
}else{
echo '网页无法正常打开,请刷新重试!!!';
}
}
/**
* 因为不是本站路径下的图,就下载图片到本地CacheImg路径并生成原路径
* 在这里吃了个大亏,微信不支持远程图片上传 必须本地路径 还有格式只能是jpg/png
*/
public function down_image($url){
$do_1=str_replace("http://","",$url);
$do_2=explode('/',$do_1);
$thumb_name=array_pop($do_2);
$domain=array_shift($do_2);
$path ='CacheImg/';
foreach($do_2 as $v){
$path.=$v.'/';
}
$pics=$path.$thumb_name;
if(!file_exists($pics)){
$dir = iconv("UTF-8", "GBK", $path);
if (!file_exists($dir)){
mkdir ($dir,0777,true);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$resource = fopen($path . $thumb_name, 'a');
fwrite($resource, $file);
fclose($resource);
}
$paths=$_SERVER['DOCUMENT_ROOT'].'/'.$pics;
return $paths;
}
/**
* 获取微信token
*/
protected function getToken($appid,$secrect){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secrect;
$token = $this->request_get($url);
$token = json_decode(stripslashes($token));
$arr = json_decode(json_encode($token), true);
$access_token = $arr['access_token'];
return $access_token;
}
/**
* 发送post请求
* @param string $url
* @param string $param
* @return bool|mixed
*/
function request_post($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch); //运行curl
curl_close($ch);
return $data;
}
/**
* 发送get请求
* @param string $url
* @return bool|mixed
*/
function request_get($url=''){
if (empty($url)) {
return false;
}
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL, $url); //抓取指定网页
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// https请求 不验证证书 其实只用这个就可以了
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
参考资料(由衷感谢以下大大们的参考):
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729
https://icharle.com/wechatmore.html