Wechat.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. if (!isset($token['openid']) && isset($token['errmsg'])) {
  52. exception($token['errmsg']);
  53. }
  54. $openid = $token['openid'] ?? '';
  55. if ($openid) {
  56. Session::set("openid", $openid);
  57. }
  58. }
  59. }
  60. }
  61. return $openid;
  62. }
  63. /**
  64. * 获取授权token网页授权
  65. *
  66. * @param string $code
  67. * @return mixed|string
  68. */
  69. public function getAccessToken($code = '')
  70. {
  71. $params = [
  72. 'appid' => $this->app_id,
  73. 'secret' => $this->app_secret,
  74. 'code' => $code,
  75. 'grant_type' => 'authorization_code'
  76. ];
  77. $ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
  78. if ($ret['ret']) {
  79. $ar = json_decode($ret['msg'], true);
  80. return $ar;
  81. }
  82. return [];
  83. }
  84. public function getJsticket($code = '')
  85. {
  86. $jsticket = Session::get('jsticket');
  87. if (!$jsticket) {
  88. $token = $this->getAccessToken($code);
  89. $params = [
  90. 'access_token' => 'token',
  91. 'type' => 'jsapi',
  92. ];
  93. $ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/ticket/getticket', $params, 'GET');
  94. if ($ret['ret']) {
  95. $ar = json_decode($ret['msg'], true);
  96. return $ar;
  97. }
  98. }
  99. return $jsticket;
  100. }
  101. }