Wechat.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace addons\epay\library;
  3. use fast\Http;
  4. use think\Cache;
  5. use think\Session;
  6. /**
  7. * 微信授权
  8. *
  9. */
  10. class Wechat
  11. {
  12. private $app_id = '';
  13. private $app_secret = '';
  14. private $scope = 'snsapi_userinfo';
  15. public function __construct($app_id, $app_secret)
  16. {
  17. $this->app_id = $app_id;
  18. $this->app_secret = $app_secret;
  19. }
  20. /**
  21. * 获取微信授权链接
  22. *
  23. * @return string
  24. */
  25. public function getAuthorizeUrl()
  26. {
  27. $redirect_uri = addon_url('epay/api/wechat', [], true, true);
  28. $redirect_uri = urlencode($redirect_uri);
  29. $state = \fast\Random::alnum();
  30. Session::set('state', $state);
  31. return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope={$this->scope}&state={$state}#wechat_redirect";
  32. }
  33. /**
  34. * 获取微信openid
  35. *
  36. * @return mixed|string
  37. */
  38. public function getOpenid()
  39. {
  40. $openid = Session::get('openid');
  41. if (!$openid) {
  42. if (!isset($_GET['code'])) {
  43. $url = $this->getAuthorizeUrl();
  44. Header("Location: $url");
  45. exit();
  46. } else {
  47. $state = Session::get('state');
  48. if ($state == $_GET['state']) {
  49. $code = $_GET['code'];
  50. $token = $this->getAccessToken($code);
  51. $openid = isset($token['openid']) ? $token['openid'] : '';
  52. if ($openid) {
  53. Session::set("openid", $openid);
  54. }
  55. }
  56. }
  57. }
  58. return $openid;
  59. }
  60. /**
  61. * 获取授权token网页授权
  62. *
  63. * @param string $code
  64. * @return mixed|string
  65. */
  66. public function getAccessToken($code = '')
  67. {
  68. $params = [
  69. 'appid' => $this->app_id,
  70. 'secret' => $this->app_secret,
  71. 'code' => $code,
  72. 'grant_type' => 'authorization_code'
  73. ];
  74. $ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
  75. if ($ret['ret']) {
  76. $ar = json_decode($ret['msg'], true);
  77. return $ar;
  78. }
  79. return [];
  80. }
  81. public function getJsticket()
  82. {
  83. $jsticket = Session::get('jsticket');
  84. if (!$jsticket) {
  85. $token = $this->getAccessToken($code);
  86. $params = [
  87. 'access_token' => 'token',
  88. 'type' => 'jsapi',
  89. ];
  90. $ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/ticket/getticket', $params, 'GET');
  91. if ($ret['ret']) {
  92. $ar = json_decode($ret['msg'], true);
  93. return $ar;
  94. }
  95. }
  96. return $jsticket;
  97. }
  98. }