心理咨询网
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WxJsSDK.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * @copyright (C)2016-2099 Hnaoyun Inc.
  4. * @author XingMeng
  5. * @email hnxsh@foxmail.com
  6. * @date 2019年05月27日
  7. * 微信网页授权
  8. */
  9. namespace core\weixin;
  10. use core\basic\Config;
  11. class WxJsSDK
  12. {
  13. protected $appid;
  14. protected $secret;
  15. protected $noncestr;
  16. public function __construct()
  17. {
  18. $this->appid = Config::get('weixin_appid');
  19. $this->secret = Config::get('weixin_secret');
  20. $this->noncestr = get_uniqid();
  21. }
  22. // 获取JsAPI签名授权信息
  23. public function getAuthInfo()
  24. {
  25. // 签名数据数组
  26. $data['jsapi_ticket'] = $this->getJsapiTicket();
  27. $data['noncestr'] = $this->noncestr;
  28. $data['timestamp'] = time();
  29. $data['url'] = get_current_url();
  30. $signature = sha1(urldecode(http_build_query($data)));
  31. // 返回数据数组
  32. $result['appid'] = $this->appid;
  33. $result['timestamp'] = $data['timestamp'];
  34. $result['noncestr'] = $this->noncestr;
  35. $result['signature'] = $signature;
  36. return $result;
  37. }
  38. // 获取访问Ticket
  39. private function getJsapiTicket()
  40. {
  41. if (! $this->checkJsapiTicket()) {
  42. $access_token = WxAccessToken::get();
  43. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
  44. $result = json_decode(get_url($url));
  45. if (isset($result->errcode) && $result->errcode) {
  46. error('获取微信JsapiTicket发生错误:' . $result->errmsg . '(' . $result->errcode . ')');
  47. return false;
  48. } else {
  49. $data['weixin_jsapi_ticket'] = $result->ticket;
  50. $data['weixin_jsapi_ticket_expires_in'] = $result->expires_in;
  51. $data['weixin_jsapi_ticket_timestamp'] = time();
  52. Config::set(sha1('weixin_jsapi_ticket'), $data); // 缓存数据
  53. return $result->ticket;
  54. }
  55. } else {
  56. return Config::get('weixin_jsapi_ticket');
  57. }
  58. }
  59. // 检查Ticket是否可用
  60. private function checkJsapiTicket()
  61. {
  62. Config::assign(RUN_PATH . '/config/' . sha1('weixin_jsapi_ticket') . '.php');
  63. if (Config::get('weixin_jsapi_ticket') && time() - Config::get('weixin_jsapi_ticket_timestamp') < Config::get('weixin_jsapi_ticket_expires_in')) {
  64. return true;
  65. } else {
  66. return false;
  67. }
  68. }
  69. }