WeChat public platform simulates login and uploads materials (turning nodejs to php for help)

Source: Internet
Author: User
Simulate login and upload materials on the public platform (turning nodejs to php for help)
MPWechat.prototype.uploadMedia = function(medianame,reqData,callback){    tools.log('uploadMedia start ...');    var boundary = 'tvmin';    var max = 9007199254740992;    var dec = Math.random() * max;    var hex = boundary + dec.toString(36);    var mimes = {        //image        '.bmp': 'image/bmp',        '.png': 'image/png',        '.gif': 'image/gif',        '.jpg': 'image/jpeg',        '.jpeg': 'image/jpeg',        /oice        '.mp3': 'audio/mp3',        '.wav': 'audio/x-wav',        '.amr': 'audior',        '.wma': 'audio/x-ms-wma',        /ideo        '.mp4': 'video/mp4',        '.rm': 'video/rm',        '.rmvb': 'videond.rn-realvideo',        '.wmv': 'video/x-ms-wmv',        '.avi': 'video/x-msvideo',        '.mpg': 'video/mpeg',        '.mpeg': 'video/mpeg'    };    var ext = path.extname(medianame).toLowerCase();    var mime = mimes[ext];    var boundaryKey = '----WebKitFormBoundary' + hex;    var payload = '\r\n\r\n--' + boundaryKey + '\r\n'        + 'Content-Disposition: form-data; name="uploadfile"; filename="'+ medianame +'"\r\n'        + 'Content-Type: '+ mime +'\r\n\r\n';    var enddata  = '\r\n--' + boundaryKey + '\r\n'        + 'Content-Disposition: form-data; name="formId"\r\n\r\n'        + '--' + boundaryKey + '--';    var contentLength = Buffer.byteLength(payload,'utf8') + reqData.length  + Buffer.byteLength(enddata,'utf8');    var options = {        host: host,        port: 443,        method: 'POST',        path: '/cgi-bin/uploadmaterial?cgi=uploadmaterial&type=0&token='+ this.token +'&t=iframe-uploadfile&lang=zh_CN&formId=null',        headers: {            'Content-Type': 'multipart/form-data; boundary='+boundaryKey,            'Content-Length': contentLength,            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31',            'Cookie': this.cookie,            'Referer': 'https://'+ host +'/cgi-bin/indexpage?token='+ this.token +'&lang=zh_CN&t=wxm-upload&lang=zh_CN&type=0&fromId=file_from_1341151893625'        }    };    var req = https.request(options, function(response) {        var statusCode = response.statusCode;//        console.log('STATUS: ' + statusCode,options);        response.setEncoding('utf8');        var data = '';        response.on('data', function(chunk) {            data += chunk;        }).on('end',function(){                callback(data.match(/formId, '(\d+)'/)[1]);            });    });    req.write(payload,'utf8');    req.write(reqData,'binary');    req.write(enddata,'utf8');    req.end();    req.on('error', function(e) {        console.error("error:"+e);    });};


The above is the code for uploading the Node. js version.

The source author says that as long as the file is changed to byte
Call the function together with the file name.
There are only two parameters.

The image format must be bmp, png, jpeg, jpg, or gif.
The Voice format must be mp3, wma, wav, and amr.
The video format must be rm, rmvb, wmv, avi, mpg, mpeg, and mp4.

I want to rewrite it to php, but it is always wrong after several days.
// Interface to upload public function pictures ($ data, $ file) {$ cookie = $ this-> read ('cookie. log'); $ cooken = self: read2 ('cooken. log'); $ https = new https; $ referer =' https://mp.weixin.qq.com/cgi-bin/indexpage?token= '; $ Referer. = $ cooken. '& lang = zh_CN & t = wxm-upload & lang = zh_CN & type = 0 & fromId = file_from_1341151893625'; // disguise source page address $ submit =' https://mp.weixin.qq.com/cgi-bin/uploadmaterial?cgi=uploadmaterial&type=0&token= '; $ Submit. = $ cooken. '& t = iframe-uploadfile & lang = zh_CN & formId = Null'; // Image submission address $ ext = strtolower (trim (substr (strrchr ($ file ,'. '), 1, 10); if ($ ext = '') return" Sorry, the file name is incorrect! "; $ Mime_types = array (// image-supported image 'bmp '=> 'image/bmp', 'PNG '=> 'image/png ', 'gif' => 'image/GIF', 'jpg '=> 'image/jpeg', 'jpeg '=> 'image/jpeg ', // audio supported by oice: 'mp3' => 'audio/MP3', 'wav '=> 'audio/x-wav', 'amr' => 'audior ', 'wma' => 'audio/x-ms-wma', // videos supported by ideo 'MP4' => 'video/mp4 ', 'RM' => 'video/rm ', 'rmvb' => 'videond. rn-realvideo', 'wmv '=> 'video/x-ms-wmv', 'Av' => 'video/x-msvideo ', 'mpg' => 'video/mpe G', 'MPEG '=> 'video/mpeg'); $ mime = isset ($ mime_types [$ ext])? $ Mime_types [$ ext]: ''; $ hexken = self: randStr (15); if (empty ($ title) {$ medianame = self :: randStr (10 ). '. '. $ ext; // Set the file name} else {$ medianame = $ file;} $ boundaryKey = '---- WebKitFormBoundary '. $ hexken; $ enddata = "\ r \ n --". $ boundaryKey. "\ r \ n"; $ enddata. = 'content-Disposition: form-data; name = "uploadfile"; filename = "'. $ medianame. '"'; $ enddata. = "\ r \ nContent-Type :". $ mime. "\ r \ n ". $ data; $ enddata. =" \ R \ n --". $ boundaryKey. "\ r \ n"; $ enddata. = 'content-Disposition: form-data; name = "formId" '; $ enddata. = "\ r \ n --". $ boundaryKey. '--'; // echo $ enddata; // file_put_contents (". /data/f1.txt ", date ('C '). "\ r \ n ". $ content. "\ r \ n", FILE_APPEND); $ result = $ https-> submit ($ submit, $ enddata, $ cookie, $ referer ); $ results = $ result ['body']; file_put_contents (". /data/data.txt ", date ('C '). "\ r \ n ". $ results. "\ r \ n", FILE_APPEND); Echo $ results; if (preg_match ("/login timeout. * log on again/", $ results) {// echo "login timeout, sending error! "; Set_time_limit (30); sleep (2); self: login (); self: qsend ($ content, $ type );} // $ result = json_decode ($ results, true); if (preg_match ("/uploaded successfully/", $ results) {echo "congratulations, the file is uploaded successfully! ";} Else if (preg_match ("/file Upload failed/", $ results) {echo" Sorry, file Upload failed! "; // Echo var_dump ($ _ SERVER); $ _ SERVER [PATH_TRANSLATED];} else {echo" failed to group! ";} Return $ result;} public function randStr ($ len = 6) {$ chars = 'abdefghjklmnpqrstvwxykfbd23456789 '; // characters to build the password from // ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789 # % * mt_srand (double) microtime () * 1000000 * getmypid ()); // seed the random number generater (must be done) $ password = ''; while (strlen ($ password) <$ len) $ password. = substr ($ chars, (mt_rand () % strlen ($ chars), 1); return $ password ;}


This is part of the code I wrote using curl_setopt.
Could you help me rewrite it?


Reply to discussion (solution)

Error? What are the prompts? Post the error message

Error? What are the prompts? Post the error message

Script document. domain = location. hostname. match (/[^ \.] *? \. [^ \.] *? $/); Var url = window. location. href, type = url. match (/[\? &] Type = ([^ &] *)/), formId = url. match (/[\? &] FormId = ([^ &] *)/); type = type [1] | 0; formId = formId [1]; top. w. upload. err ("failed to upload file", type, formId); script
Sorry, an error occurred while uploading the file!

This is returned if the login information is correct or incorrect.


Thank you!

I would like to ask, how is your simulated login code written, I use Snoopy simulated login, passed to the http://mp.weixin.qq.com/cgi-bin/login? Lang = zh_CN: username, pwd, f, and imgcode always return unsuccessful logon. why? Are some cookies still required?

I would like to ask, how is your simulated login code written, I use Snoopy simulated login, passed to the http://mp.weixin.qq.com/cgi-bin/login? Lang = zh_CN: username, pwd, f, and imgcode always return unsuccessful logon. why? Are some cookies still required?
Snoopy is useless, and now it's useless to update these simulations on the platform!
Let's take a look at the interface first. if you have applied for an application, you can use the interface directly.
If this is not the case, we will be able to attack the public platform again!

$url = "https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&ticket_id={$username}&ticket={$ticket}&token={$this->token}&lang=zh_CN";    $this->send_data = array(    'action' => 'upload_material',    'ticket_id' => $username,    'ticket' => $ticket,    'token' => $this->token,    'ajax' => 1,    'file' =>"@".str_replace('/', '\\', $_SERVER['DOCUMENT_ROOT'])."\\uploads\\file\\20140324104305420.jpg",    'folder' => '/cgi-bin/uploads',    'Upload' => 'Submit Query',    't' =>'ajax-response',    );    print_r($this->send_data);    $this->getHeader = 1;    $this->referer = "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=10&isMul=0&isNew=1&lang=zh_CN&token={$this->token}";//'https://mp.weixin.qq.com/cgi-bin/advanced?action=dev&t=advanced/dev&token='.$this->token.'&lang=zh_CN';                return $this->curlPostFile($url);;

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.