WordPress发布文章同步到新浪微博失败的问题解决与分享

次阅读

张戈博客很久之前分享过一篇 WordPress 发布文章同步到新浪微博 的文章,但经常有站长留言反馈同步失败,我一直觉得是代码部署问题。

最近很长一段时间,张戈博客也无法同步,我又觉得是微博自身的问题。直到近期抽空 DeBUG 了一下微博同步,取得了返回结果,才发现是由于网站 IP 变更导致的!

一、网站 IP 变更

如下是我 DeBUG 取得的返回 json 结果:

weibo13

格式化如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
{
    "headers": {
        "server": "nginx/1.6.1",
        "date": "Sat, 16 Jan 2016 11:43:34 GMT",
        "content-type": "application/json;charset=UTF-8",
        "connection": "close",
        "api-server-ip": "10.75.5.90",
        "vary": "Accept-Encoding"
    },
    "body": "{\"error\":\"Ip Limit, request ip is not contained in safety ip\",\"error_code\":10004,\"request\":\"/2/statuses/upload_url_text.json\"}",
    "response": {
        "code": 400,
        "message": "Bad Request"
    },
    "cookies": [ ],
    "filename": null
}

其中 “Ip Limit, request ip is not contained in safety ip” 很明显的指出了错误原因:当前 IP 不在微博服务器白名单列表当中,说白了就是网站换了 IP 地址,和你之前申请微博应用时填写的 IP 不一致了!

前往新浪微博开放平台看了下,里面设置的 IP 果然还是之前的老 IP:

weibo11

所以,如果发现你部署了代码,却总是无法同步,请前往 微博开放平台,如图查看并更正一下网站现用服务器的IP地址。

当然,修改后会进入二次审核状态,耐心等待好了。 weibo12

Ps:其实最后我发现这里可以不填写任何 IP,免得下次网站更换服务器又忘记修改了!反正大部分人也不怕自己的微博被盗用。

二、DeBUG 方法

如果,上述分享还不能解决你的问题,最后张戈再分享本文用到的 DeBUG 方法。

原理很简单,所谓的 DeBUG 就是取得微博同步的返回值,看下到底是什么原因不能同步。DeBUG 代码如下:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* WordPress发布文章同步到新浪微博(DeBUG测试)
* 文章地址:/5082.html
*/
ini_set('display_errors', true);
require('./wp-blog-header.php');
header("Content-type: text/html;charset=UTF-8");
header('HTTP/1.1 200 OK');

function post_to_sina_weibo_test($post_ID) {
   $get_post_info = get_post($post_ID);
   $get_post_centent = get_post($post_ID)->post_content;
   $get_post_title = get_post($post_ID)->post_title;
   if ($get_post_info->post_status == 'publish') {
       $appkey='1034947262'; /* 此处是你的新浪微博appkey,不修改的话就会显示来自张戈博客哦! */
       $username='微博用户名';
       $userpassword='微博密码';
       $request = new WP_Http;
       $keywords = "";

       /* 获取文章标签关键词 */
       $tags = wp_get_post_tags($post_ID);
       foreach ($tags as $tag ) {
          $keywords = $keywords.'#'.$tag->name."#";
       }

      /* 修改了下风格,并添加文章关键词作为微博话题,提高与其他相关微博的关联率 */
     $string1 = '【文章发布】' . strip_tags( $get_post_title ).':';
     $string2 = $keywords.' 查看全文:'.get_permalink($post_ID);

     /* 微博字数控制,避免超标同步失败 */
     $wb_num = (138 - WeiboLength_test($string1.$string2))*2;
     $status = $string1.mb_strimwidth(strip_tags( apply_filters('the_content', $get_post_centent)),0, $wb_num,'...').$string2;
       /* 获取特色图片,如果没设置就抓取文章第一张图片 */
       $url = get_mypost_thumbnail($post_ID);

       /* 判断是否存在图片,定义不同的接口 */
       if(!empty($url)){
          $api_url = 'https://api.weibo.com/2/statuses/upload_url_text.json'; /* 新的API接口地址 */
          $body = array('status' => $status,'source' => $appkey,'url' => $url);
       } else {
          $api_url = 'https://api.weibo.com/2/statuses/update.json';
          $body = array('status' => $status,'source' => $appkey);
       }
       $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
       $result = $request->post($api_url, array('body' => $body,'headers' => $headers));
       return json_encode($result);
    }
}
/*
//获取微博字符长度函数
*/
function WeiboLength_test($str)
{
    $arr = arr_split_zh_test($str);   //先将字符串分割到数组中
    foreach ($arr as $v){
        $temp = ord($v);        //转换为ASCII码
        if ($temp > 0 && $temp < 127) {
            $len = $len+0.5;
        }else{
            $len ++;
        }
    }
    return ceil($len);        //加一取整
}
/*
//拆分字符串函数,只支持 gb2312编码
//参考:http://u-czh.iteye.com/blog/1565858
*/
function arr_split_zh_test($tempaddtext){
    $tempaddtext = iconv("UTF-8", "GBK//IGNORE", $tempaddtext);
    $cind = 0;
    $arr_cont=array();
    for($i=0;$i<strlen($tempaddtext);$i++)
    {
        if(strlen(substr($tempaddtext,$cind,1)) > 0){
            if(ord(substr($tempaddtext,$cind,1)) < 0xA1 ){ //如果为英文则取1个字节
                array_push($arr_cont,substr($tempaddtext,$cind,1));
                $cind++;
            }else{
                array_push($arr_cont,substr($tempaddtext,$cind,2));
                $cind+=2;
            }
        }
    }
    foreach ($arr_cont as &$row)
    {
        $row=iconv("gb2312","UTF-8",$row);
    }
    return $arr_cont;
}

/**
* WordPress 获取文章图片加强版 By 张戈博客
*/
if(!function_exists('get_mypost_thumbnail')){
  function get_mypost_thumbnail($post_ID){
     if (has_post_thumbnail()) {
            $timthumb_src = wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), 'full' );
            $url = $timthumb_src[0];
    } else {
        if(!$post_content){
            $post = get_post($post_ID);
            $post_content = $post->post_content;
        }
        preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', do_shortcode($post_content), $matches);
        if( $matches && isset($matches[1]) && isset($matches[1][0]) ){
            $url =  $matches[1][0];
        }else{
            $url =  '';
        }
    }
    return $url;
  }
}
echo post_to_sina_weibo_test(5082); //此处数字改成博客已发布文章的ID即可

先根据自己微博修改以上代码中的微博 app_key、用户名、密码。

然后,将最后一句代码中的 5082 改成你博客已发布文章的 ID。

最后,将代码保存为 php 文件(比如 test.php),上传到网站根目录并在浏览器访问即可看到微博同步返回的结果了!

能看到失败原因,相信问题已经解决了一半,是不是又学到了一招呢?

三、https 导致失败

早上发现 IP 变更已经审核通过了,就更新文章试了下,还是没有同步成功!呐尼?

然后,又试了下 DeBUG 大法,发现返回如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
{
    "headers": {
        "server": "nginx/1.6.1",
        "date": "Tue, 19 Jan 2016 02:40:01 GMT",
        "content-type": "application/json;charset=UTF-8",
        "connection": "close",
        "api-server-ip": "10.75.5.68",
        "vary": "Accept-Encoding"
    },
    "body": "{\"error\":\"does multipart has image?\",\"error_code\":20007,\"request\":\"/2/statuses/upload_url_text.json\"}",
    "response": {
        "code": 400,
        "message": "Bad Request"
    },
    "cookies": [],
    "filename": null
}

error:does multipart has image? 什么鬼??

网上找了半天,基本都是说图片不是本地的,或者上传封装得不对之类的。

于是,强行将 $url 这个变量指定为具体图片地址,发现还是这个错误:

1
$url= '/logo.png';

甚至,直接试了下图片的本地物理路径也不行。

最终,发现把 https 改成 http 就好了!!!原来不支持 https 图片?

那我把 $url 中的 https 强行替换成 http 就好了:

1
$url = preg_replace('/https:\/\//i','http://',$url);

果然,替换后就成功了:

weibo3weibo4

如果还是不行,请留言联系张戈!

最后更新于 2016年3月17日星期四