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
- Interface for obtaining permanent material list: material/batchget_material
- Add permanent material Interface: material/add_news
- Added the media file Interface material/add_material.
- Graphic Type
- 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 '<br/>'; $ 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 '<br/>'; 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 for your learning and support for helping customers.