AuthService.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * 微信授权服务
  4. * Class AuthService
  5. * Author SHUI
  6. * @package alipayAop
  7. */
  8. define('WEIXIN_SDK_DIR', __DIR__);
  9. require_once WEIXIN_SDK_DIR . '/lib/WxPay.Config.php';
  10. class AuthService {
  11. public function getOpenidFromWeixin($code) {
  12. $url = $this->_createOauthUrl($code);
  13. $res = self::curlGet($url);
  14. $data = json_decode($res, true);
  15. $openid = isset($data['openid']) ? $data['openid'] : '';
  16. return $openid;
  17. }
  18. private function _createOauthUrl($code) {
  19. $data = [
  20. 'appid' => WxPayConfig::APPID,
  21. 'secret' => WxPayConfig::APPSECRET,
  22. 'code' => $code,
  23. 'grant_type' => 'authorization_code'
  24. ];
  25. $queryStr = $this->_buildUrlParam($data);
  26. return "https://api.weixin.qq.com/sns/oauth2/access_token?{$queryStr}";
  27. }
  28. private function _buildUrlParam($data) {
  29. $buff = '';
  30. foreach ( $data as $k => $v ) {
  31. if ( 'sign' != $k ) {
  32. $buff .= "{$k}={$v}&";
  33. }
  34. }
  35. return trim($buff, '&');
  36. }
  37. public static function curlGet($url = '', $options = []) {
  38. $ch = curl_init();
  39. curl_setopt($ch, CURLOPT_URL, $url);
  40. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  41. curl_setopt($ch, CURLOPT_HEADER, 0);
  42. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  43. if ( !empty($options) ) {
  44. curl_setopt_array($ch, $options);
  45. }
  46. //https请求 不验证证书和host
  47. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  48. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  49. $data = curl_exec($ch);
  50. curl_close($ch);
  51. return $data;
  52. }
  53. }