3,143
社区成员
发帖
与我相关
我的任务
分享
// 上传图文消息代码
$raw = Curl::curl_post_wx( 'https://api.weixin.qq.com/cgi-bin/material/add_news?access_token='
. $token, self::json_article( $post_ids, $token ), false );
/**
* 将文章内容构造成json字符串
*
* @param array $post_ids
* @param string $token
* @return string json
*/
private function json_article( $post_ids, $token ) {
$mp_article = '{"articles":[';
foreach ( $post_ids as $post_id ) {
$post = get_post( $post_id );
$post_urls = self::preg_match_src( $post->post_content );
if ( $post_urls ) {
// 如果文章中有图片,将文章中的图片上传至微信素材库
foreach ( $post_urls as $post_url ) {
if ( strpos( $post_url, 'qpic.cn' ) === false ) {
// 如果图片没有上传到微信服务器
$res = Curl::curl_post_wx( 'https://api.weixin.qq.com/cgi-bin/material/add_material?'
. 'access_token=' . $token . '&type=image', false, Curl::curl_get_img( $post_url ) );
//替换文章内容img中的src地址
$post->post_content = str_replace( $post_url, $res['url'], $post->post_content );
}
$post->post_content = str_replace( '"', '\"', $post->post_content );
}
}
// 获取缩略图并上传
// 相应的code省略
// 构造json
$mp_article .= '{
"title": "' . $post->post_title . '",
"content_source_url": "' . get_permalink( $post_id, false ) . '",
"thumb_media_id": "' . $thumb_res['media_id'] . '",
"content": "' . htmlspecialchars_decode( $post->post_content ) . '",
"show_cover_pic": 0,
';
if ( !empty($post->post_excerpt ) ) {
$mp_article .= '"digest": "' . $post->post_excerpt . '",';
}
$mp_article .= '},';
}
return rtrim($mp_article, ',') . ']}';
}
foreach ($news as &$item){
foreach ($item as $k=>$v){
if($k =='content'){
$item[$k] = urlencode(htmlspecialchars(str_replace("\"","'",$v)));
}else{
$item[$k] = urlencode($v);
}
}
}
$data=array("articles"=>$news);
$data=json_encode($data);
$end_data= urldecode($data);
$end_data= htmlspecialchars_decode($end_data);
if ( $post_urls ) {
// 如果文章中有图片,将文章中的图片上传至微信素材库
foreach ( $post_urls as $post_url ) {
if ( strpos( $post_url, 'qpic.cn' ) === false ) {
// 如果图片没有上传到微信服务器
$res = Curl::curl_post_wx( 'https://api.weixin.qq.com/cgi-bin/material/add_material?'
. 'access_token=' . $token . '&type=image', false, Curl::curl_get_img( $post_url ) );
//替换文章内容img中的src地址
$post->post_content = str_replace( $post_url, $res['url'], $post->post_content );
}
}
// 下面这个替换应该放在foreach外,否则有多张图片时会进行多次替换
$post->post_content = str_replace( '"', '\"', $post->post_content );
}