Use php to call WeChat interface to upload permanent materials

Source: Internet
Author: User
This article describes how to use the php call interface to upload permanent materials. This article describes how to use the php call interface to upload permanent materials,

Functional requirements

The newly opened public account of the company needs to import all the excellent articles on the company's platform. Manual import requires a lot of work, so the automatic synchronization of articles is used to achieve the effect.

Development instructions

Open api provides an interface for adding permanent materials. This function is based on this interface for data synchronization.

Used interface

  1. Interface for obtaining permanent material list: material/batchget_material

  2. Add permanent material interface: material/add_news

  3. Added the media file interface material/add_material.

  4. Graphic type

  5. Single text (requires a default cover, which must be uploaded to the public account background in advance)

Environment requirements

Php version: less than 5.5 (because the following code must upload a media file in this environment, otherwise the interface will fail to be called)

Development process

1. obtain a list of all articles from the company platform
2. traverse the article list to check whether there are image attachments in the article. if there is any picture attachment, perform step 3. otherwise, perform step 4.
3. check all attachments, retrieve the first image attachment, and call the new media file interface to upload the image to obtain the returned media_id.
4. call the Clip List interface to obtain the default cover image and obtain media_id from the obtained data.
5. call the upload image and text interface to upload materials based on the media_id obtained in the returned result.
6. record the returned information

Interface Design

Interface for obtaining the Clip List

This interface is used to obtain the default image media_id data synchronization platform data interface

This interface is used to synchronize data in our own articles to implement the function.

Interface constant


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?';

Interface for obtaining the Clip List

Action Interface Method

Note: This method is the interface entry method.

Call method: http: // $ {domain}/weixin/get_articles/


/*** Image obtaining interface */public function get_articles_action () {$ token = $ this-> get_access_token (); $ list = $ this-> getForeverList ($ token, 'Image',); echo json_encode ($ list);} get_access_token method 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 ;}

Call material interface method

Note: This method is used to call the interface for obtaining the permanent clip list.


/*** Obtain the permanent Clip List * @ param $ token * @ param $ type. the types include image, vedio, and audio * @ param $ offset start position, 0 indicates the number of @ param $ count from the first *, with a range of 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 ['errorcode']) {$ this-> errCode = $ json ['errcode']; $ this-> errMsg = $ json ['errmsg ']; return false;} return $ json ;} return false ;}

Synchronize articles to the interface

Action method

Note: This method is the interface entry method.

Call method: http: // $ {domain}/weixin/upload_article/


/*** Synchronize the Q & A article to the subscription number interface */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) {// filter and obtain the first image if ($ a ['is _ image']) {$ attache = $; break ;}$ img = $ attache ['path']; $ size = filesize ($ img); echo $ img. ', size is :'. $ size; echo'
'; $ File_info = array ('filename' => $ img, 'Content-type' => 'image/jpg ', // file type 'filelength '=> $ size); $ upload_img_result = $ this-> upload_meterial ($ file_info, $ access_token); $ media_id = $ upload_img_result; error_log ('media _ id is ===================> '. $ media_id);} else {$ media_id = '1potp0sqruwwu _ HX0HR_jUp4STX5HSpYkibb1Ca8ZQA ';} $ articles = array (); // when the image is uploaded successfully, start uploading the image and text $ upload_article_data = array ('title' => $ article ['title'], 'thumb _ media_id '=> $ media_id, 'author' => 'eggplant nutritionist ', 'Digest' => 'eggplant life, your quality life Guide', 'show _ cover_pic '=> 1, 'content' => $ article ['message'], 'content _ source_url '=> $ base_url. $ article ['id']); $ articles [] = $ upload_article_data; $ data = array ('Articles '=> $ articles ); $ result = $ this-> uploadForeverArticles ($ access_token, $ data); echo self: json_encode ($ result); error_log ('upload _ article result is :'. json_encode ($ result )); error_log ('========================== upload end ====== ================================= ');}}

UploadForeverArticles method

Note: This method is used to call the permanent material Upload interface.


/*** Upload permanent graphic materials (the authenticated subscription number is available) * You can also see * @ param array $ data message structure {"articles": [{...}]} in the Material Management module of the official website of the public platform. * @ return boolean | array */public function uploadForeverArticles ($ access_token, $ data) {error_log ('post data is =====> '. self: json_encode ($ data); $ url = self: API_URL_PREFIX.self: MEDIA_FOREVER_NEWS_UPLOAD_URL. 'access _ token = '. $ access_token; $ result = HTTP: request ($ url, 'post', self: json_encode ($ d Ata); error_log ('weixin return result is ===> '. $ result); if ($ result) {$ json = json_decode ($ result, true); if (! $ Json |! Empty ($ json ['errcode']) {$ this-> errcode = $ json ['errcode']; $ this-> errMsg = $ json ['errmsg ']; return false;} return $ json;} return false ;}

Upload_meterial method

Note: This method is used to call the permanent material Upload interface.


/*** Note that this method must ensure that the php version is earlier than 5.6, otherwise the 40015 error will pop up */function upload_meterial ($ file_info, $ access_token) {$ url = "https://api.weixin.qq.com/cgi-bin/material/add_material? Access_token = {$ access_token} & type = image "; $ token = curl_init (); $ timeout = 5; $ real_path =" {$ file_info ['filename']} "; // $ real_path = str_replace ("/", "\", $ real_path); $ data = array ("media" => "@ {$ real_path }", 'form-data' => $ file_info); curl_setopt ($ scheme, CURLOPT_URL, $ url); curl_setopt ($ scheme, CURLOPT_POST, 1); curl_setopt ($ scheme, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ scheme, CURLOPT_CONNECTTIMEOUT, $ timeout); curl_setopt ($ scheme, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ scheme, scheme, false); curl_setopt ($ scheme, CURLOPT_POSTFIELDS, $ data); $ result = curl_exec ($ response); echo'
'; Echo 'reulst is =========> '. $ result; curl_close ($ rows); if (curl_errno () = 0) {$ result = json_decode ($ result, true); // var_dump ($ result ); return $ result ['media _ id'];} else {return false ;}}

Http_post method

Description: This method is used to call an http post request.


/*** POST request * @ param string $ url * @ param array $ param * @ param boolean $ post_file whether to upload files * @ return string content */private function http_post ($ url, $ param, $ post_file = false) {$ oCurl = curl_init (); if (stripos ($ url, "https ://")! = FALSE) {curl_setopt ($ oCurl, success, 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 ;}}

Problems encountered

During the development process, when you call the upload media file, the returned data is always


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

Cause: The php version is incorrect. my local version is 5.6, and the php method with @ recognition must be less than 5.5 for recognition. the php method above 5.5 will remove this feature.

Solution: change the php version to 5.5 or below. the method for not changing the php version is not found yet.

The above is all the content of this article. I hope it will be helpful to everyone's learning, and I hope you can support your own home.

The above is a detailed description of the use of php to call the interface to upload permanent materials. For more information, see other articles on php Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.