WeixinServer.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. <?php
  2. namespace App\Servers;
  3. use App\Models\ErrorRecord;
  4. use App\Servers\Weixin\Unifiedorder;
  5. use Illuminate\Support\Facades\Cache;
  6. use function Couchbase\defaultDecoder;
  7. class WeixinServer
  8. {
  9. static private $server = null;
  10. public $mch_id = '';
  11. public $private_key = '';
  12. public $cert_file = '';
  13. public $key_file = '';
  14. public $appid = '';
  15. public $appsecret = '';
  16. public $appletId = '';
  17. public $appletKey = '';
  18. function __construct()
  19. {
  20. $this->mch_id=env('WX_MCH_ID','');
  21. $this->private_key=env('WX_PRIVATE_KEY','');
  22. $this->appid=env('WX_APPID','');
  23. $this->appsecret=env('WX_APPSECRET','');
  24. $this->cert_file=env('WX_CERT_FILE','');
  25. $this->key_file=env('WX_KEY_FILE','');
  26. $this->appletId=env('APPLET_ID','');
  27. $this->appletKey=env('APPLET_KEY','');
  28. }
  29. /**
  30. * 创建对象
  31. * @return WeixinServer
  32. */
  33. static function creatServer()
  34. {
  35. if (empty(self::$server)) self::$server = new WeixinServer();
  36. return self::$server;
  37. }
  38. /**
  39. * 发送模板消息
  40. * @param $data
  41. */
  42. function sendTemplate($data)
  43. {
  44. $access_token = $this->getAccessToken();
  45. $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
  46. $result = $this->sendRequest($url, 'post', $data);
  47. $result = json_decode($result, true);
  48. if ($result['errcode'] == 0) {
  49. //消息发放成功
  50. } else {
  51. //消息发放失败
  52. ErrorRecord::create(['m_id' => 0, 'msg' => '模板消息推送失败', 'data' => json_encode($data)]);
  53. ErrorRecord::create(['m_id' => 0, 'msg' => '模板消息推送失败', 'data' => json_encode($result)]);
  54. }
  55. return $result;
  56. }
  57. /**
  58. * 根据openid获取会员信息
  59. * @param $openid
  60. * @return false|mixed
  61. */
  62. function getUserInfo($openid)
  63. {
  64. $access_token = $this->getAccessToken();
  65. $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
  66. $result = $this->sendRequest($url, 'get');
  67. $result = json_decode($result, true);
  68. if (empty($result['openid'])) {
  69. //消息发放成功
  70. return $result;
  71. } else {
  72. //消息发放失败
  73. ErrorRecord::create(['m_id' => 0, 'msg' => '接口获取会员用户信息失败', 'data' => $openid]);
  74. return false;
  75. }
  76. }
  77. /**
  78. * 获取会员微信细腻
  79. * @return false|\Illuminate\Contracts\Foundation\Application|\Illuminate\Session\SessionManager|\Illuminate\Session\Store|mixed
  80. */
  81. function getOpenId()
  82. {
  83. $openid = session('wx_openid');
  84. if ($openid) return $openid;
  85. $code = request()->input('code', '');
  86. if (!isset($code)) {
  87. $redirect_url = $this->getServerUrl();
  88. $redirect_url = urlencode($redirect_url);
  89. $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
  90. redirect($url);
  91. return false;
  92. } else {
  93. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
  94. $result = $this->sendRequest($url);
  95. $result = json_decode($result, true);
  96. if (isset($result['errcode'])) {
  97. return false;
  98. } else {
  99. $openid = $result['openid'];
  100. $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token={$result['refresh_token']} ";
  101. $result = $this->sendRequest($url);
  102. $result = json_decode($result, true);
  103. if (isset($result['access_token'])) {
  104. return $result['openid'];
  105. }
  106. session(['wx_openid' => $openid]);
  107. return $openid;
  108. }
  109. }
  110. }
  111. /**
  112. * 小程序code获取openid等信息
  113. * @param $code
  114. * @param $invite_code
  115. * @return array|false
  116. */
  117. function getAppletsOpenId($code){
  118. $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appletId}&secret={$this->appletKey}&js_code={$code}&grant_type=authorization_code";
  119. $result = $this->sendRequest($url);
  120. $result = json_decode($result, true);
  121. if ( !isset($result['openid'])) {//成功返回信息
  122. return ['code'=>0,'msg'=>$result['errmsg']];
  123. } else {
  124. return $result;
  125. }
  126. }
  127. /**
  128. * 网页授权
  129. * @return mixed
  130. */
  131. function authorize()
  132. {
  133. $code = request()->input('code', '');
  134. if (empty($code)) {
  135. $redirect_url = $this->getServerUrl();
  136. $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  137. $this->redirect($url);
  138. return false;
  139. } else {
  140. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
  141. $result = $this->sendRequest($url);
  142. $result = json_decode($result, true);
  143. if (isset($result['errcode'])) {
  144. return false;
  145. } else {
  146. $openid = $result['openid'];
  147. $access_token = $result['access_token'];
  148. $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token={$result['refresh_token']} ";
  149. $result = $this->sendRequest($url);
  150. $result = json_decode($result, true);
  151. if (isset($result['access_token'])) {
  152. $access_token = $result['access_token'];
  153. $openid = $result['openid'];
  154. }
  155. $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
  156. $result = $this->sendRequest($url);
  157. $result = json_decode($result, true);
  158. if (isset($result['errcode'])) {
  159. return false;
  160. }
  161. return $result;
  162. }
  163. }
  164. }
  165. function redirect($uri = '', $method = 'location', $http_response_code = 302)
  166. {
  167. if (!preg_match('#^https?://#i', $uri)) {
  168. $uri = site_url($uri);
  169. }
  170. switch ($method) {
  171. case 'refresh' :
  172. header("Refresh:0;url=" . $uri);
  173. break;
  174. default :
  175. header("Location: " . $uri, TRUE, $http_response_code);
  176. break;
  177. }
  178. exit();
  179. }
  180. /**
  181. * 获取小程序码
  182. * @param $page //页面路径
  183. * @param $scene //携带参数
  184. */
  185. function getAppletCode($page,$scene){
  186. $access_token = $this->getAccessToken(2);
  187. $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
  188. $data['page'] = $page;
  189. $data['scene'] = $scene;
  190. $data['check_path'] = false;
  191. $data['width'] = 300;
  192. $result = $this->sendRequest($url,'post',$data);
  193. return $result;
  194. }
  195. /**
  196. * 获取 access_token
  197. * @return bool
  198. */
  199. protected function getAccessToken($type = 1)
  200. {
  201. if($type == 1){
  202. $key = 'vouchername';
  203. $appId = $this->appid;
  204. $appsecret = $this->appsecret;
  205. }else{
  206. $key = 'applet_voucher';
  207. $appId = $this->appletId;
  208. $appsecret = $this->appletKey;
  209. }
  210. $data = RedisDataServer::creatServer()->getData($key, 'json');
  211. if (empty($data) || $data['endtime'] < time()) {
  212. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appsecret}";
  213. $result = $this->sendRequest($url);
  214. $result = json_decode($result, true);
  215. // $bey = Cache::set('vouchername', array('access_token' => $result['access_token'], 'endtime' => time() + 7000), 7000);
  216. if ( isset($result['access_token'])) {
  217. RedisDataServer::creatServer()->setData($key, array('access_token' => $result['access_token'], 'endtime' => time() + 1800), 'json',1800);
  218. return $result['access_token'];
  219. } else {
  220. return false;
  221. }
  222. } else {
  223. return $data['access_token'];
  224. }
  225. }
  226. /**
  227. * 获取js授权信息
  228. * @return mixed
  229. */
  230. function getJsConfig($url = '')
  231. {
  232. $hash = '';
  233. $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz';
  234. $max = strlen($chars) - 1;
  235. for ($i = 0; $i < 16; $i++) {
  236. $hash .= $chars[mt_rand(0, $max)];
  237. }
  238. $data['noncestr'] = $hash;
  239. $data['jsapi_ticket'] = $this->getJsTicket();
  240. $data['timestamp'] = time();
  241. if (empty($url)) {
  242. $data['url'] = $this->getServerUrl();
  243. } else {
  244. $data['url'] = $url;
  245. }
  246. ksort($data);
  247. $str = '';
  248. foreach ($data as $key => $val) {
  249. $str .= '&';
  250. $str .= $key . '=' . $val;
  251. }
  252. $str = mb_substr($str, 1);
  253. $data['appid'] = $this->appid;
  254. $data['signature'] = sha1($str);
  255. unset($data['jsapi_ticket']);
  256. return $data;
  257. }
  258. /**
  259. * 获取当前连接
  260. * @return string
  261. */
  262. function getServerUrl()
  263. {
  264. // $http_host=request()->header('host');
  265. // $data=request()->all();
  266. return urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
  267. // return 'http://'.$http_host. '?' . http_build_query($data);;
  268. }
  269. /**
  270. * 获取Js调用凭证
  271. * @return bool
  272. */
  273. function getJsTicket()
  274. {
  275. // $data = Cache::get('js_ticket');
  276. $data = RedisDataServer::creatServer()->getData('js_ticket', 'json');
  277. if (empty($data) || $data['endtime'] < time()) {
  278. $access_token = $this->getAccessToken();
  279. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
  280. $result = $this->sendRequest($url);
  281. $result = json_decode($result, true);
  282. if ($result['errcode'] == 0) {
  283. //file_put_contents($this->js_ticket,serialize(array('access_token'=>$result['access_token'],'endtime'=>time()+7000)));
  284. // Cache::set('js_ticket', array('access_token' => $result['ticket'], 'endtime' => time() + 7000), 7000);
  285. RedisDataServer::creatServer()->setData('js_ticket', array('access_token' => $result['ticket'], 'endtime' => time() + 7000), 'json',7000);
  286. return $result['ticket'];
  287. }
  288. return false;
  289. } else {
  290. return $data['access_token'];
  291. }
  292. }
  293. /**
  294. * 微信签名
  295. */
  296. function wxSign($data, $keys)
  297. {
  298. ksort($data);
  299. $str = '';
  300. foreach ($data as $key => $val) {
  301. if ($val) {
  302. if ($str != '') $str .= '&';
  303. $str .= "{$key}={$val}";
  304. }
  305. }
  306. $str .= '&key=' . $keys;
  307. $sign = strtoupper(MD5($str));
  308. return $sign;
  309. }
  310. /**
  311. * @param $url
  312. * @param string $type 请求方式
  313. * @param string $data 数据 数组格式
  314. * @return mixed
  315. */
  316. protected function sendRequest($url, $type = 'get', $data = '')
  317. {
  318. $ch = curl_init();
  319. if ($type == 'get' && $data) {
  320. $url = $url . '?' . http_build_query($data);
  321. }
  322. curl_setopt($ch, CURLOPT_URL, $url); //设置访问路径
  323. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //设置可以返回字符串
  324. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  325. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  326. $head = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36');
  327. curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
  328. if ($type == 'post') {
  329. curl_setopt($ch, CURLOPT_POST, TRUE);//post请求
  330. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  331. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置传递的参数
  332. }
  333. $request = curl_exec($ch);
  334. curl_close($ch);
  335. return $request;
  336. }
  337. /**
  338. * JS支付签名
  339. * @param $order_sn
  340. * @param $total_fee
  341. * @param $notify_url
  342. * @param $body
  343. * @param $wx_openid
  344. * @return bool
  345. */
  346. public function wxJsPay($order_sn, $total_fee, $notify_url, $body, $wx_openid = '')
  347. {
  348. $is_test=env('TEST_SERVE',false);
  349. if($is_test)$total_fee = 0.01;
  350. $conf = array(
  351. 'appid' => $this->appid,
  352. 'mch_id' => $this->mch_id,
  353. 'notify_url' => $notify_url,
  354. 'openid' => $wx_openid,
  355. 'out_trade_no' => $order_sn,
  356. 'total_fee' => $total_fee * 100,
  357. 'trade_type' => 'JSAPI',
  358. 'body' => $body,
  359. );
  360. $order = new Unifiedorder($conf);
  361. $request = $order->getOrder($this->private_key);
  362. if ($request['code'] == 1) {
  363. $datas["appId"] = $request['data']['appid'];
  364. $datas["nonceStr"] = $order->getNonceStr();
  365. $datas["package"] = "prepay_id={$request['data']['prepay_id']}";
  366. $datas["signType"] = 'MD5';
  367. $datas["timeStamp"] = time();
  368. $s = $order->wxSign($datas, $this->private_key);
  369. $datas["paySign"] = $s;
  370. return $datas;
  371. } else {
  372. return false;
  373. }
  374. }
  375. /**
  376. * JS支付签名
  377. * @param $order_sn
  378. * @param $total_fee
  379. * @param $notify_url
  380. * @param $body
  381. * @param $wx_openid
  382. * @return bool
  383. */
  384. public function getPayOrder($order_sn)
  385. {
  386. $is_test=env('TEST_SERVE',false);
  387. if($is_test)$total_fee = 0.01;
  388. $cert_file=base_path($this->cert_file);
  389. $key_file=base_path($this->key_file);
  390. $conf = array(
  391. 'appid' => $this->appid,
  392. 'mch_id' => $this->mch_id,
  393. 'out_trade_no' => $order_sn,
  394. );
  395. $order = new Unifiedorder($conf, ['cert_file' => $cert_file, 'key_file' => $key_file]);
  396. $request = $order->getPayOrder($this->private_key);
  397. return $request;
  398. }
  399. /**
  400. * 微信验签
  401. * @param $data
  402. * @return string
  403. */
  404. function verifyCer($data)
  405. {
  406. if (isset($data['sign'])) unset($data['sign']);
  407. $conf = array(
  408. 'appid' => $this->appid,
  409. 'mch_id' => $this->mch_id,
  410. );
  411. $order = new Unifiedorder($conf);
  412. $sign = $order->wxSign($data, $this->private_key);
  413. return $sign;
  414. }
  415. /**
  416. * 微信退款
  417. * @param $total_fee
  418. * @param $out_trade_no
  419. * @param string $body
  420. * @param int $order_money
  421. * @return array
  422. */
  423. function wxPayRefund($out_trade_no, $total_fee, $body = '',$order_money=0)
  424. {
  425. $is_test=env('TEST_SERVE',false);
  426. if($is_test){
  427. $total_fee = 0.01;
  428. $order_money = 0.01;
  429. }
  430. $conf = array(
  431. 'appid' => $this->appid,
  432. 'mch_id' => $this->mch_id,
  433. 'out_trade_no' => $out_trade_no,
  434. 'out_refund_no' => 'T'.$out_trade_no.time(),
  435. 'total_fee' => $order_money * 100,
  436. 'refund_fee' => $total_fee * 100,
  437. 'refund_desc' => $body
  438. );
  439. $order = new Unifiedorder($conf, ['cert_file' => base_path($this->cert_file), 'key_file' => base_path($this->key_file)]);
  440. $request = $order->wxPayRefund($this->private_key);
  441. ErrorRecord::create(['m_id' =>0, 'msg' => '微信退款失败', 'data' => json_encode($request)]);
  442. if ($request['code'] == 1) {
  443. return ['code' => 1, 'msg' => '退款成功', 'data' => ['ret_sn' => $request['data']['refund_id']]];
  444. } else {
  445. return ['code' => 0, 'msg' => '微信退款失败', 'data' => ['ret_sn' => '']];
  446. }
  447. }
  448. /**
  449. * 微信付款到零钱
  450. * @param $order_sn
  451. * @param $total_fee
  452. * @param $openid
  453. * @param $body
  454. * @return array
  455. */
  456. function setVerified($order_sn, $total_fee, $openid, $body)
  457. {
  458. $cert_file=base_path($this->cert_file);
  459. $key_file=base_path($this->key_file);
  460. $private_key=$this->private_key;
  461. $conf = array(
  462. 'mch_appid' => $this->appid,
  463. 'mchid' => $this->mch_id,
  464. 'openid' => $openid,
  465. 'partner_trade_no' => $order_sn,
  466. 'amount' => $total_fee * 100,
  467. 'check_name' => 'NO_CHECK',
  468. 'desc' => $body,
  469. );
  470. $order = new Unifiedorder($conf, ['cert_file' => $cert_file, 'key_file' => $key_file]);
  471. $request = $order->setVerified($private_key);
  472. ErrorRecord::create(['m_id' =>0, 'msg' => '微信提现记录', 'data' => json_encode($request)]);
  473. return $request;
  474. }
  475. }