/** * 转换微信格式content * @method getWechatContent * @since 0.0.1 * @return {string} * @example $this->getWechatContent(); */ protected function getWechatContent() { $content = $this->content; if (preg_match_all('/<img.*?[\\/]?>/i', $content, $imgs)) { $urls = []; foreach ($imgs[0] as $img) { if (preg_match_all('/(?<=src|_src|data-src)(?:\\s*=\\s*")(.*?)(?=")/i', $img, $srcs) && isset($srcs[1]) && $srcs[1]) { $urls = array_merge($urls, $srcs[1]); } } if ($urls) { $urls = array_unique($urls); foreach ($urls as $url) { $image = WechatNewsImage::findOne($this->manager->addNewsImage($url)); if ($image) { $content = str_replace($image->url_source, $image->url, $content); } } } } return $content; }
/** * 上传图文消息内的图片 * * @since 0.0.1 * @param {string} $url_source 源url(非微信端) * @return {integer} * @example \Yii::$app->wechat->addNewsImage($url_source); */ public function addNewsImage($url_source) { if ($image = WechatNewsImage::findOne(['appid' => $this->app->appid, 'url_source' => $url_source])) { return $image->id; } $image = new WechatNewsImage(); $image->url_source = $url_source; $data = $this->getData('/cgi-bin/media/uploadimg', ['access_token' => $this->getAccessToken()], ['media' => '@' . $image->localFile]); $image->cleanTmp(); if ($this->errcode == 0) { $image->appid = $this->app->appid; $image->url = $data['url']; if ($image->save()) { return $image->id; } } return 0; }