寫了一天,掉了好多坑,不過還是寫出來了
問題總結下:
1、php版本問題
2、微信上傳圖片路徑問題
3、同步內容到素材庫的array問題
//Author: echo <[email protected]>
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