Home WeChat Applet WeChat Development Detailed explanation of using PHP to call the WeChat interface to upload permanent materials

Detailed explanation of using PHP to call the WeChat interface to upload permanent materials

Apr 12, 2017 pm 03:23 PM
php upload WeChat interface transfer

这篇文章主要介绍了详解使用php调用微信接口上传永久素材,

功能需求

公司新开的公众号需要将公司平台现在的所有精品文章都导入,手动导入会有很多的工作量,所以采用自动化同步文章的方式来达到效果

开发说明

微信open api提供了新增永久素材的接口,本次功能是基于这个接口进行数据同步的

使用到的接口

  1. 获取永久素材列表接口:material/batchget_material

  2. 新增永久素材接口:material/add_news

  3. 新增媒体文件接口:material/add_material

  4. 图文类型

  5. 单图文(要求有默认的封面,需要提前上传到微信公众号后台)

环境要求

php版本:5.5以下(因为下面代码中的上传媒体文件必须要求在此环境,否则会调用微信接口失败)

开发流程

1、从公司平台获取所有的文章列表
2、遍历文章列表,查看文章是否有图片附件,若有进行第三步,否则进行第四步
3、检测所有的附件,取出第一个图片附件,并调用新增媒体文件接口上传图片获得返回后的media_id
4、调用素材列表接口获取默认的封面图片,并从中得到的数据中获取media_id
5、根据返回获取到的media_id开始调用上传图文接口上传素材
6、记录返回信息

接口设计

获取微信素材列表接口

此接口是用于获取默认的图片media_id同步平台数据接口

此接口是用户同步我们自己的文章数据到微信功能实现

接口常量


private $app_id = 'wx189ae9fa8816b131';
private $app_secret = '36f5f430c591acbae3505fe877733283';
const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
const MEDIA_FOREVER_UPLOAD_URL = '/material/add_material?';
const MEDIA_FOREVER_NEWS_UPLOAD_URL = '/material/add_news?';
const MEDIA_FOREVER_NEWS_UPDATE_URL = '/material/update_news?';
const MEDIA_FOREVER_GET_URL = '/material/get_material?';
const MEDIA_FOREVER_DEL_URL = '/material/del_material?';
const MEDIA_FOREVER_COUNT_URL = '/material/get_materialcount?';
const MEDIA_FOREVER_BATCHGET_URL = '/material/batchget_material?';
Copy after login

获取微信素材列表接口

action接口方法

说明:该方法为此接口的入口方法

调用方式:http://${domain}/weixin/get_articles/


 /**
   * 获取图片素材接口
   */
  public function get_articles_action(){
   $token = $this->get_access_token();
   $list = $this->getForeverList($token,'image',0,20);
   echo json_encode($list);
  }
  get_access_token方法
  
  private function get_access_token() {
   $access_token = AWS_APP::cache()->get('access_token');
   if(!$access_token){
    error_log('get access_token from weixin ');
    $appId = $this->app_id;
    $appSecret = $this->app_secret;
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
    $res = json_decode($this -> httpGet($url));
    $access_token = $res -> access_token;
    AWS_APP::cache()->set('access_token',$access_token,time()+3600);
   }else{
    error_log('get access_token from cache ');
   }
   error_log('access_token is :'.$access_token);
   return $access_token;
  }
Copy after login

调用微信素材接口方法

说明:该方法为调用微信获取永久素材列表接口方法


 /**
  * 获取永久素材列表
  * @param $token
  * @param $type 类型有image,vedio和audio
  * @param $offset 起始位置,0表示从第一个
  * @param $count 个数,区间为0~20
  */
  public function getForeverList($token,$type,$offset,$count){
   $data = array(
    'type' => $type,
    'offset' => $offset,
    'count' => $count,
   );
   $result = $this->http_post(
         self::API_URL_PREFIX.self::MEDIA_FOREVER_BATCHGET_URL.'access_token='.$token,
         self::json_encode($data)
         );
   error_log('forever list is :'.$result);
   if ($result)
   {
    $json = json_decode($result,true);
    if (isset($json['errcode'])) {
    $this->errCode = $json['errcode'];
    $this->errMsg = $json['errmsg'];
    return false;
    }
    return $json;
   }
   return false;
  }
Copy after login

同步文章到微信接口

action方法

说明:该方法为此接口的入口方法

调用方式:http://${domain}/weixin/upload_article/


/**
 * 同步问答的文章到订阅号上接口
 */
public function index_action(){
 $article_list = $this->model('article')->get_articles_list(null, 1, 18, 'add_time DESC');
 $access_token = $this->get_access_token();
 $base_url = 'http://wenda.qiezilife.com/article/';
 foreach ($article_list as $key => $article){

  if($article['has_attach']){
   $attaches = $this->model('publish')->get_attach('article', $article['id'], 'max');
   foreach ($attaches as $i => $a){
    //过滤获取第一张图片
    if($a['is_image']){
     $attache = $a;
     break;
    }
   }

   $img = $attache['path'];
   $size = filesize($img);
   echo $img.',size is :'.$size;
   echo &#39;<br/>&#39;;
   $file_info = array(
    &#39;filename&#39; => $img,
    &#39;content-type&#39; => &#39;image/jpg&#39;, //文件类型
    &#39;filelength&#39; => $size
   );
   $upload_img_result = $this->upload_meterial($file_info,$access_token);
   $media_id = $upload_img_result;
   error_log(&#39;media_id is ===============>&#39;.$media_id);
  }else{
   $media_id = &#39;1PoTp0SqruwWu_HX0HR_jUp4STX5HSpYkibb1Ca8ZQA&#39;;
  }

  $articles =array();
  //上传图片成功了就开始上传图文
  $upload_article_data = array(
   &#39;title&#39; => $article[&#39;title&#39;],
   &#39;thumb_media_id&#39; => $media_id,
   &#39;author&#39; => &#39;茄子营养师&#39;,
   &#39;digest&#39; => &#39;茄子生活,你的品质生活指南&#39;,
   &#39;show_cover_pic&#39; => 1,
   &#39;content&#39; => $article[&#39;message&#39;],
   &#39;content_source_url&#39; => $base_url.$article[&#39;id&#39;]
  );

  $articles[] = $upload_article_data;

  $data = array(
   &#39;articles&#39; => $articles
  );
  $result= $this->uploadForeverArticles($access_token,$data);
  echo self::json_encode($result);
  error_log(&#39;upload_article result is : &#39;.json_encode($result));
  error_log(&#39;============================upload end============================&#39;);

  }
}
Copy after login

uploadForeverArticles方法

说明:该方法为调用微信上传永久素材接口方法


/**
 * 上传永久图文素材(认证后的订阅号可用)
 * 新增的永久素材也可以在公众平台官网素材管理模块中看到
 * @param array $data 消息结构{"articles":[{...}]}
 * @return boolean|array
 */
public function uploadForeverArticles($access_token,$data){
 error_log(&#39;post data is=======> &#39;.self::json_encode($data));
 $url = self::API_URL_PREFIX.self::MEDIA_FOREVER_NEWS_UPLOAD_URL.&#39;access_token=&#39;.$access_token;
 $result = HTTP::request($url, &#39;POST&#39;, self::json_encode($data));
 error_log(&#39;weixin return result is =====>&#39;.$result);
 if ($result)
 {
  $json = json_decode($result,true);
  if (!$json || !empty($json[&#39;errcode&#39;])) {
   $this->errCode = $json[&#39;errcode&#39;];
   $this->errMsg = $json[&#39;errmsg&#39;];
   return false;
  }
  return $json;
 }
 return false;
}
Copy after login

upload_meterial方法

说明:该方法为调用微信上传永久素材接口方法


  /**
   * 请注意该方法必须保证php的版本在5.6以下,否则会爆40015错误
   */
  function upload_meterial($file_info,$access_token){
   $url="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$access_token}&type=image";
   $ch1 = curl_init ();
   $timeout = 5;
   $real_path="{$file_info[&#39;filename&#39;]}";
   //$real_path=str_replace("/", "\\", $real_path);
   $data= array("media"=>"@{$real_path}",&#39;form-data&#39;=>$file_info);
   curl_setopt ( $ch1, CURLOPT_URL, $url );
   curl_setopt ( $ch1, CURLOPT_POST, 1 );
   curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
   curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
   curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
   curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
   curl_setopt ( $ch1, CURLOPT_POSTFIELDS, $data );
   $result = curl_exec ( $ch1 );
   echo &#39;<br/>&#39;;
   echo &#39;reulst is ==========>&#39;.$result;
   curl_close ( $ch1 );
   if(curl_errno()==0){
    $result=json_decode($result,true);
    //var_dump($result);
    return $result[&#39;media_id&#39;];
   }else {
    return false;
   }
  }
Copy after login

http_post方法

说明:该方法为调http post请求方法


/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
private function http_post($url,$param,$post_file=false){
 $oCurl = curl_init();
 if(stripos($url,"https://")!==FALSE){
  curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
 }
 if (is_string($param) || $post_file) {
  $strPOST = $param;
 } else {
  $aPOST = array();
  foreach($param as $key=>$val){
   $aPOST[] = $key."=".urlencode($val);
  }
  $strPOST = join("&", $aPOST);
 }
 curl_setopt($oCurl, CURLOPT_URL, $url);
 curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
 curl_setopt($oCurl, CURLOPT_POST,true);
 curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
 $sContent = curl_exec($oCurl);
 $aStatus = curl_getinfo($oCurl);
 curl_close($oCurl);
 if(intval($aStatus["http_code"])==200){
  return $sContent;
 }else{
  return false;
 }
}
Copy after login

遇到的问题

在开发的过程中,在调用微信上传媒体文件时候始终得到的返回数据为


{"errcode":41005,"errmsg":"media data missing hint: [3fSt_0048e297]"}
Copy after login

原因:php版本的问题,我本机的版本5.6,而带有@识别的php方法必须是5.5以下才能识别,5.5以上的版本将这个特性去除了。

解决方法:更换php的版本到5.5或者5.5以下,不更换php的版本的方法暂时没有找到

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

The above is the detailed content of Detailed explanation of using PHP to call the WeChat interface to upload permanent materials. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What is the difference between an abstract class and an interface in PHP? What is the difference between an abstract class and an interface in PHP? Apr 08, 2025 am 12:08 AM

The main difference between an abstract class and an interface is that an abstract class can contain the implementation of a method, while an interface can only define the signature of a method. 1. Abstract class is defined using abstract keyword, which can contain abstract and concrete methods, suitable for providing default implementations and shared code. 2. The interface is defined using the interface keyword, which only contains method signatures, which is suitable for defining behavioral norms and multiple inheritance.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles