UploadAble.php
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* Created by PhpStorm.
* User: HanSon
* Date: 2017/1/9
* Time: 16:18
*/
namespace Hanson\Robot\Message;
/**
* Class UploadAble
* @package Hanson\Robot\Message\
*
* @property string static $mediaCount
*/
trait UploadAble
{
/**
* @param $username
* @param $file
* @return bool|mixed|string
*/
public static function uploadMedia($username, $file)
{
$url = 'https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json';
static::$mediaCount = ++static::$mediaCount;
$lastModifyDate = gmdate('D M d Y H:i:s TO', filemtime($file));
list($mime, $mediaType) = static::getMediaType($file);
$data = [
'id' => 'WU_FILE_' .static::$mediaCount,
'name' => $file,
'type' => $mime,
'lastModifieDate' => $lastModifyDate,
'size' => filesize($file),
'mediatype' => $mediaType,
'uploadmediarequest' => json_encode([
'BaseRequest' => server()->baseRequest,
'ClientMediaId' => time(),
'TotalLen' => filesize($file),
'StartPos' => 0,
'DataLen' => filesize($file),
'MediaType' => 4,
// 'UploadType' => 2,
// 'FromUserName' => myself()->username,
// 'ToUserName' => $username,
// 'FileMd5' => md5_file($file)
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
'webwx_data_ticket' => static::getTicket(),
'pass_ticket' => server()->passTicket,
'filename' => '@'.$file
];
$result = http()->post($url, $data, true);
print_r($data);
print_r($result);
if($result['BaseResponse']['Ret'] == 0){
return $result;
}
return false;
}
private static function getMediaType($file)
{
$info = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($info, $file);
finfo_close($info);
return [$mime, explode('/', $mime)[0] === 'image' ? 'pic' : 'doc'];
}
private static function getTicket()
{
$cookies = http()->getClient()->getConfig('cookies')->toArray();
$key = array_search('webwx_data_ticket', array_column($cookies, 'Name'));
return $cookies[$key]['Value'];
}
}