Home Backend Development PHP Tutorial WeChat message sending

WeChat message sending

Jul 25, 2016 am 08:49 AM

Simulate logging in to WeChat users to obtain user groups and send messages
  1. error_reporting( E_ALL ^ ​​E_NOTICE );
  2. // Instructions for use:
  3. // Start by logging in
  4. $param = array();
  5. $param['username'] = 'username';
  6. $param['pwd'] = 'password';
  7. echo '
    ';
  8. $wx = new Weixin();
  9. $flag = $wx->login($param);
  10. echo "Login:n";
  11. var_dump($flag);
  12. echo "n";
  13. echo "Get group:n";
  14. $group = $wx->getGroup();
  15. var_dump($group);
  16. echo "n";
  17. echo "Group members:n";
  18. $group = $wx->getFriendByGroup('0');
  19. var_dump($group);
  20. echo "n";
  21. echo "Latest Message n";
  22. $msg = $wx->newmesg();
  23. var_dump($msg);
  24. echo "n";
  25. echo "Get image and text:n";
  26. $mesg = $wx-> getMsg();
  27. var_dump($mesg);
  28. echo "n";
  29. echo "Send message: n";
  30. // Description: If $content is text, send a text message
  31. // Description: If $content is text If the image and text ID is used, the image and text message will be sent
  32. //$content = 'test text'; // Text
  33. //$content = '10000023'; // Image and text material id
  34. //$mesg = $wx->batchMesgByGroup ('101', $content);
  35. //var_dump($mesg);
  36. $arr = array(
  37. 'fakeId'=>'985865180',
  38. "nickName"=>"逄jintao",
  39. "remarkName" =>'',
  40. 'content'=>'10000002'
  41. );
  42. $s=$wx->sendmesg($arr);
  43. var_dump($s);
  44. echo "df";
  45. /* *
  46. * WeChat public platform operation
  47. * Based on PHP-CURL
  48. *
  49. * @author phpbin
  50. *
  51. */
  52. class Weixin
  53. {
  54. /**
  55. * PHP curl header part
  56. *
  57. * @var array
  58. */
  59. private $_header;
  60. /**
  61. * Communication cookie
  62. *
  63. * @var string
  64. */
  65. private $_cookie;
  66. /**
  67. * token
  68. *
  69. * @var string
  70. * /
  71. private $_token;
  72. /**
  73. * Initialization, set header
  74. */
  75. public function __construct()
  76. {
  77. $this->_header = array();
  78. $this->_header[] = "Host:mp .weixin.qq.com";
  79. $this->_header[] = "Referer:https://mp.weixin.qq.com/cgi-bin/getmessage";
  80. }
  81. /**
  82. * User login
  83. * Structure $param = array('username'=>'', 'pwd'=>'');
  84. *
  85. * @param array $param
  86. * @return boolean
  87. */
  88. public function login($param)
  89. {
  90. $url = 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN';
  91. $post = 'username='.urlencode ($param['username']).'&pwd='.md5($param['pwd']).'&imgcode=&f=json';
  92. $stream = $this->_html($url, $post );
  93. // Determine whether the login is successful
  94. $html = preg_replace("/^.*{/is", "{", $stream);
  95. $json = json_decode($html, true);
  96. // Get token
  97. preg_match("/lang=zh_CN&token=(d+)/is", $json['ErrMsg'], $match);
  98. $this->_token = $match[1];
  99. // Get cookie
  100. $this->_cookie($stream);
  101. return (boolean)$this->_token;
  102. }
  103. /**
  104. * Get graphic messages
  105. *
  106. * @return array
  107. */
  108. public function getMsg()
  109. {
  110. $url = 'https ://mp.weixin.qq.com/cgi-bin/operate_appmsg?token='.$this->_token.'&lang=zh_CN&sub=list&type=10&subtype=3&t=wxm-appmsgs-list-new&pagesize=10&pageidx=0&lang =zh_CN';
  111. $stream = $this->_html($url);
  112. // Analyze friends in groups
  113. preg_match_all('/"appId":"(d+)".*?"title":"( .*?)".*?/is', $stream, $matches);
  114. if ( !is_array($matches[1])) return false;
  115. $returns = array();
  116. foreach ( $matches[ 1] as $key=>$val) {
  117. $temp = array();
  118. $returns[$matches[1][$key]] = $matches[2][$key];
  119. }
  120. return $ returns;
  121. }
  122. /**
  123. * Get platform grouping
  124. *
  125. * @return array
  126. */
  127. public function getGroup()
  128. {
  129. $url = 'https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize =10&pageidx=0&type=0&groupid=0&token='.$this->_token.'&lang=zh_CN';
  130. $stream = $this->_html($url);
  131. // Grouping
  132. preg_match('/" groups":(.*?)\}).groups/is', $stream, $match);
  133. $jsonArr = json_decode($match[1], true);
  134. $returns = array();
  135. foreach ( $jsonArr as $key=>$val) {
  136. $returns[$val['id']] = $val['name'].'('.$val['cnt'].')';
  137. }
  138. return $returns;
  139. }
  140. /**
  141. * Get group members
  142. *
  143. * @param integer $gId
  144. * @return array;
  145. */
  146. public function getFriendByGroup($gId)
  147. {
  148. $url = 'https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid='.$gId.'&token='.$this->_token.'&lang=zh_CN';
  149. $stream = $this->_html($url);
  150. // 分析分组中好友
  151. preg_match('/"contacts":(.*?)\}).contacts/is', $stream, $match);
  152. $jsonArr = json_decode($match[1], true);
  153. if ( !is_array($jsonArr)) return false;
  154. $returns = array();
  155. foreach ( $jsonArr as $key=>$val) {
  156. $temp = array();
  157. $temp['fakeId'] = $val['id'];
  158. $temp['nickName'] = $val['nick_name'];
  159. $temp['remarkName'] = $val['remark_name'];
  160. $returns[] = $temp;
  161. }
  162. return $returns;
  163. }
  164. /**
  165. * Send in batches in groups
  166. *
  167. * @param integer $gId group ID
  168. * @param string $content
  169. * @return array
  170. */
  171. public function battchMesgByGroup($gId, $content)
  172. {
  173. $mebInfo = $this->getFriendByGroup($gId);
  174. if ( false == $mebInfo) return false;
  175. // 循环发送
  176. $returns = array();
  177. foreach ( $mebInfo as $key=>$val)
  178. {
  179. $val['content'] = $content;
  180. $this->sendmesg($val) ? $returns['succ'] ++ : $returns['err']++;
  181. }
  182. return $returns;
  183. }
  184. /**
  185. * Send message
  186. *
  187. * Structure $param = array(fakeId, content, msgId);
  188. * @param array $param
  189. * @return boolean
  190. */
  191. public function sendmesg($param)
  192. {
  193. $url = 'https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response';
  194. // 分类型进行推送
  195. if ( (int)$param['content']>100000)
  196. {
  197. $post = 'error=false&tofakeid='.$param['fakeId'].'&type=10&fid='.$param['content'].'&appmsgid='.$param['content'].'&quickreplyid='.$param['msgId'].'&token='.$this->_token.'&ajax=1';
  198. } else {
  199. $post = 'error=false&tofakeid='.$param['fakeId'].'&type=1&content='.$param['content'].'&quickreplyid='.$param['msgId'].'&token='.$this->_token.'&ajax=1';
  200. }
  201. $this->_header[1] = "Referer:https://mp.weixin.qq.com/cgi-bin/singlemsgpage?msgid=&source=&count=20&t=wxm-singlechat&fromfakeid=".$param['fakeId']."&token=".$this->_token;
  202. $stream = $this->_html($url, $post);
  203. // 是不是设置成功
  204. $html = preg_replace("/^.*{/is", "{", $stream);
  205. $json = json_decode($html, true);
  206. return (boolean)$json['msg'] == 'ok';
  207. }
  208. /**
  209. * Extract cookies from Stream
  210. *
  211. * @param string $stream
  212. */
  213. private function _cookie($stream)
  214. {
  215. preg_match_all("/Set-Cookie: (.*?);/is", $stream, $matches);
  216. $this->_cookie = @implode(";", $matches[1]);
  217. }
  218. /**
  219. * Get Stream
  220. *
  221. * @param string $url
  222. * @param string $post
  223. * @return mixed
  224. */
  225. private function _html($url, $post = FALSE)
  226. {
  227. ob_start();
  228. $ch = curl_init($url);
  229. curl_setopt($ch, CURLOPT_HEADER, true);
  230. curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_header);
  231. curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  232. if ( $post){
  233. curl_setopt($ch, CURLOPT_POST, true);
  234. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  235. }
  236. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  237. curl_setopt($ch, CURLOPT_COOKIE, $this->_cookie);
  238. //curl_setopt($ch, CURLOPT_PROXY, 'http://10.100.10.100:3128');
  239. curl_exec($ch);
  240. curl_close($ch);
  241. $_str = ob_get_contents();
  242. $_str = str_replace("script", "", $_str);
  243. ob_end_clean();
  244. return $_str;
  245. }
  246. /**
  247. * Get the latest news
  248. *
  249. * Return structure: id:msgId; fakeId; nickName; content;
  250. *
  251. * @return array
  252. */
  253. public function newmesg()
  254. {
  255. $url = 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token='.$this->_token;
  256. $stream = $this->_html($url);
  257. preg_match('/"msg_item":(.*?)\}).msg_item/is', $stream, $match);
  258. $jsonArr = json_decode($match[1], true);
  259. $returns = array();
  260. foreach ( $jsonArr as $val){
  261. if ( isset($val['is_starred_msg'])) continue;
  262. $returns[] = $val;
  263. }
  264. return $returns;
  265. }
  266. }
复制代码


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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles