weixinjs.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. declare (strict_types=1);
  3. namespace library\lib;
  4. class weixinjs {
  5. private $appId = '';
  6. private $appSecret = '';
  7. public function __construct() {
  8. if(empty($info)) $info = config('weixin');
  9. $this->appId = $info['APPID'];
  10. $this->appSecret = $info['APPSECRET'];
  11. }
  12. public function getSignPackage() {
  13. $jsapiTicket = $this->getJsApiTicket();
  14. // 注意 URL 一定要动态获取,不能 hardcode.
  15. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  16. $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  17. //var_dump($url);
  18. //$url = C('SYS_URL').$_SERVER[REQUEST_URI];
  19. $timestamp = time();
  20. $nonceStr = $this->createNonceStr();
  21. // 这里参数的顺序要按照 key 值 ASCII 码升序排序
  22. $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
  23. $signature = sha1($string);
  24. $signPackage = array(
  25. "appId" => $this->appId,
  26. "nonceStr" => $nonceStr,
  27. "timestamp" => $timestamp,
  28. "url" => $url,
  29. "signature" => $signature,
  30. "rawString" => $string
  31. );
  32. return $signPackage;
  33. }
  34. public function addrSign($signPackage) {
  35. $sdata = array(
  36. 'appId' => $signPackage['appId'],
  37. 'url' => $signPackage['url'],
  38. 'timeStamp' => $signPackage['timestamp'],
  39. 'nonceStr' => $signPackage['nonceStr'],
  40. 'accessToken' => $signPackage['access_token']
  41. );
  42. ksort($sdata);
  43. $string = "";
  44. foreach ($sdata as $k => $v) {
  45. $string.=strtolower($k) . "=" . $v . '&';
  46. }
  47. $string = substr($string, 0, -1);
  48. return sha1($string);
  49. }
  50. /**
  51. * 获取模板
  52. */
  53. public function template($tempId,$openid, $data,$return_url = '') {
  54. $accessToken = $this->getAccessToken();
  55. $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken;
  56. $post_data['touser'] = $openid;
  57. $post_data['template_id'] =$tempId; //模板订单
  58. //$_A['sys']['sys_url'] . '/User/order_info?trade_no=' . $trade_no
  59. if (!empty($return_url))
  60. $post_data['url'] = $return_url;
  61. $post_data['topcolor'] = '#FF0000';
  62. $post_data['data'] = $data;
  63. $r_data = $this->httpPost($url, $this->Xjson_encode($post_data));
  64. return $r_data;
  65. }
  66. /**
  67. * 获取验证码
  68. */
  69. public function showqrcode($id) {
  70. $accessToken = $this->getAccessToken();
  71. $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $accessToken;
  72. $data = $this->httpPost($url, '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "' . $id . '"}}}');
  73. $data_json = json_decode($data, true);
  74. if ($data_json['errcode'] != '40013') {
  75. $url = $data_json['url'];
  76. $ticket = $data['ticket'];
  77. $urlx = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket;
  78. $this->httpGet($urlx);
  79. return $url;
  80. }
  81. return '';
  82. }
  83. /**
  84. * 发送客服消息
  85. */
  86. function sendMsg($openid, $text) {
  87. $accessToken = $this->getAccessToken();
  88. $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $accessToken;
  89. $post_data['touser'] = $openid;
  90. $post_data['msgtype'] = 'text';
  91. $post_data['text'] = array('content' => $text);
  92. $data = $this->httpPost($url, $this->Xjson_encode($post_data));
  93. if ($data['errcode'] == 0) {
  94. return array('errcode' => 0);
  95. } else {
  96. return $data;
  97. }
  98. }
  99. /**
  100. * 发送图片
  101. */
  102. function sendImage( $openid,$media_id) {
  103. $accessToken = $this->getAccessToken();
  104. $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $accessToken;
  105. $post_data['touser'] = $openid;
  106. $post_data['msgtype'] = 'image';
  107. $post_data['image'] = array("media_id"=>$media_id);
  108. $data = $this->httpPost($url, $this->Xjson_encode($post_data));
  109. $data = json_decode($data,true);
  110. if ($data['errcode'] == 0) {
  111. return array('errcode' => 0);
  112. } else {
  113. return $data;
  114. }
  115. }
  116. /**
  117. * 上传文件
  118. * @param type $fielname
  119. */
  120. function UpdateImage($path){
  121. $accessToken = $this->getAccessToken();
  122. $data = '@'.realpath($path).";type=image/jpeg;filename=".md5(time()).".jpg";
  123. $datx = $this->uploadFile($data,'image',$accessToken);
  124. $datx = json_decode($datx, true);
  125. if($datx['media_id']){
  126. return $datx;
  127. } else {
  128. return null;
  129. }
  130. }
  131. /**
  132. * 用户信息
  133. * @param type $openid
  134. * @return type
  135. */
  136. function userinfo($openid) {
  137. $accessToken = $this->getAccessToken();
  138. $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $accessToken . '&openid=' . $openid . '&lang=zh_CN';
  139. $data = $this->httpGet($url);
  140. $data_json = json_decode($data, true);
  141. if ($data_json['errcode'] != '40013') {
  142. return $data_json;
  143. } else {
  144. return null;
  145. }
  146. }
  147. /**
  148. * 设置menu
  149. * @param type $data
  150. */
  151. function SetMenu($data) {
  152. $accessToken = $this->getAccessToken();
  153. $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $accessToken;
  154. $post_data = $data;
  155. $datax = $this->httpPost($url, $this->Xjson_encode($post_data));
  156. return $datax;
  157. }
  158. /**
  159. * 获取客服基本信息
  160. */
  161. function getkflist() {
  162. $accessToken = $this->getAccessToken();
  163. $url = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=' . $accessToken;
  164. $data = $this->httpGet($url);
  165. $data_json = json_decode($data, true);
  166. return $data_json;
  167. }
  168. /**
  169. * 获取在线客服接待信息
  170. * @return type
  171. */
  172. function getonlinekflist() {
  173. $accessToken = $this->getAccessToken();
  174. $url = 'https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=' . $accessToken;
  175. $data = $this->httpGet($url);
  176. $data_json = json_decode($data, true);
  177. return $data_json;
  178. }
  179. /**
  180. * 添加客服账号
  181. * @param type $data
  182. * @return type
  183. */
  184. function kfaccount_add($data){
  185. $accessToken = $this->getAccessToken();
  186. $url = 'https://api.weixin.qq.com/customservice/kfaccount/add?access_token='.$accessToken;
  187. $post_data = $data;
  188. $datax = $this->httpPost($url, $this->Xjson_encode($post_data));
  189. return $datax;
  190. }
  191. /**
  192. * 设置客服信息
  193. * @param type $data
  194. * @return type
  195. */
  196. function kfaccount_save($data){
  197. $accessToken = $this->getAccessToken();
  198. $url = 'https://api.weixin.qq.com/customservice/kfaccount/update?access_token='.$accessToken;
  199. $post_data = $data;
  200. $datax = $this->httpPost($url, $this->Xjson_encode($post_data));
  201. return $datax;
  202. }
  203. /**
  204. * 删除数据
  205. * @param type $kf_account
  206. * @return type
  207. */
  208. function kfaccount_del($kf_account) {
  209. $accessToken = $this->getAccessToken();
  210. $url = 'https://api.weixin.qq.com/customservice/kfaccount/del?access_token=' . $accessToken . '&kf_account=' . $kf_account;
  211. $data = $this->httpGet($url);
  212. $data_json = json_decode($data, true);
  213. return $data_json;
  214. }
  215. /**
  216. *
  217. * @param type $length
  218. * @return type
  219. */
  220. private function createNonceStr($length = 16) {
  221. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  222. $str = "";
  223. for ($i = 0; $i < $length; $i++) {
  224. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  225. }
  226. return $str;
  227. }
  228. private function getJsApiTicket() {
  229. // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
  230. $data = json_decode(cache('weix_jsapi_ticket'),true);
  231. if ( empty($data) && $data['expire_time'] < time()) {
  232. $accessToken = $this->getAccessToken();
  233. // 如果是企业号用以下 URL 获取 ticket
  234. // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
  235. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
  236. $res = json_decode($this->httpGet($url));
  237. $ticket = $res->ticket;
  238. if ($ticket) {
  239. $data['expire_time'] = time() + 7000;
  240. $data['jsapi_ticket'] = $ticket;
  241. cache('weix_jsapi_ticket', json_encode($data));
  242. }
  243. } else {
  244. $ticket = $data['jsapi_ticket'];
  245. }
  246. return $ticket;
  247. }
  248. private function getAccessToken() {
  249. // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
  250. $data = [];
  251. $weixAccessToken = cache('weix_access_token');
  252. $data = empty($weixAccessToken) ? '' : json_decode($weixAccessToken,true);
  253. if (empty($data) || $data['expire_time'] < time()) {
  254. // 如果是企业号用以下URL获取access_token
  255. // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
  256. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
  257. $res = json_decode($this->httpGet($url));
  258. $access_token = $res->access_token;
  259. $data = [];
  260. if (!empty($access_token)) {
  261. $data['expire_time'] = time() + 7000;
  262. $data['access_token'] = $access_token;
  263. cache('weix_access_token', json_encode($data));
  264. }
  265. } else {
  266. $access_token = $data['access_token'];
  267. }
  268. return $access_token;
  269. }
  270. /* 上传多媒体文件 */
  271. public function uploadFile($file, $type = 'image', $acctoken = '') {
  272. $post_data ['type'] = $type; // 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
  273. $post_data ['media'] = $file;
  274. $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$acctoken&type=image";
  275. $ch = curl_init();
  276. curl_setopt($ch, CURLOPT_POST, 1);
  277. curl_setopt($ch, CURLOPT_URL, $url);
  278. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  279. ob_start();
  280. curl_exec($ch);
  281. $result = ob_get_contents();
  282. ob_end_clean();
  283. return $result;
  284. }
  285. private function httpGet($url) {
  286. $curl = curl_init();
  287. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  288. curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  289. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  290. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  291. curl_setopt($curl, CURLOPT_URL, $url);
  292. $res = curl_exec($curl);
  293. curl_close($curl);
  294. return $res;
  295. }
  296. private function httpPost($url, $post) {
  297. $curl = curl_init();
  298. curl_setopt($curl, CURLOPT_URL, $url);
  299. curl_setopt($curl, CURLOPT_HEADER, false);
  300. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  301. curl_setopt($curl, CURLOPT_NOBODY, true);
  302. curl_setopt($curl, CURLOPT_POST, true);
  303. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  304. $return_str = curl_exec($curl);
  305. curl_close($curl);
  306. return $return_str;
  307. }
  308. function Xjson_encode($input) {
  309. // 从 PHP 5.4.0 起, 增加了这个选项.
  310. return json_encode($input, JSON_UNESCAPED_UNICODE);
  311. }
  312. }