GetWeixinToken.class.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Cas\Controller\CmdLine;
  3. use KIF\Core\Controller;
  4. use KIF\Cache\Memcached;
  5. use KIF\Core\Config;
  6. /**
  7. * 获取微信Token
  8. * 执行:php /www/index.php -cCmdLine_GetWeixinToken
  9. * @author lihuanchun
  10. */
  11. class GetWeixinToken extends Controller{
  12. private $accessTokenCacheName ;
  13. private $jsApiTicketCacheName ;
  14. private $appId ;
  15. private $appSecret ;
  16. private $thisTime ;
  17. private $objMemcached;
  18. public function run() {
  19. $action = $this->action;
  20. $this->$action();
  21. }
  22. /**
  23. * 初始化
  24. *
  25. */
  26. public function __construct(){
  27. $this->objMemcached = new Memcached();
  28. $this->thisTime = time();
  29. $wechat_cfg = Config::getInstance()->get('wechat_cfg');
  30. $this->appSecret = $wechat_cfg['appSecret'];
  31. $this->appId = $wechat_cfg['appId'];
  32. $this->jsApiTicketCacheName ='weixin_jsApiTicke';
  33. $this->accessTokenCacheName = 'weixin_AccessToken';
  34. }
  35. /**
  36. * 每小时执一次:php /www/index.php -cCmdLine_GetWeixinToken
  37. */
  38. public function doDefault(){
  39. # 统一执行
  40. $accessToken = $this->getAccessToken();
  41. $jsApiTicket = $this->getJsApiTicket($accessToken);
  42. print "
  43. 时间:".date("Y-m-d H:i:s")."
  44. 计算结果:\n
  45. accessToken: {$accessToken}\n
  46. jsApiTicket: {$jsApiTicket}\n
  47. ";
  48. }
  49. /**
  50. * 获取微信 AccessToken 存入 Memcached
  51. */
  52. public function getAccessToken(){
  53. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
  54. $res = json_decode($this->httpGet($url));
  55. $accessToken = $res->access_token;
  56. $this->objMemcached -> set($this->accessTokenCacheName, $accessToken);
  57. return $accessToken;
  58. }
  59. /**
  60. * 获取微信 JsApiTicket 存入 Memcached
  61. */
  62. public function getJsApiTicket($accessToken){
  63. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
  64. $res = json_decode($this->httpGet($url));
  65. $jsApiTicket = $res->ticket;
  66. $this->objMemcached -> set($this->jsApiTicketCacheName, $jsApiTicket);
  67. return $jsApiTicket;
  68. }
  69. /**
  70. * curl 请求
  71. */
  72. private function httpGet($url) {
  73. $curl = curl_init();
  74. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  75. curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  76. curl_setopt($curl, CURLOPT_URL, $url);
  77. $res = curl_exec($curl);
  78. curl_close($curl);
  79. return $res;
  80. }
  81. }