Base.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace wx;
  3. class Base
  4. {
  5. /**
  6. * 获取普通token
  7. * @param $appid
  8. * @param $secret
  9. * @return mixed
  10. */
  11. public function getAccessToken($appid, $secret)
  12. {
  13. $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret.'';
  14. $res = $this->curl($url);
  15. $res = json_decode($res, true);
  16. if(isset($res['errcode'])){
  17. trace($res, 'error');
  18. return null;
  19. }
  20. return $res['access_token'];
  21. }
  22. /**
  23. * 请求接口
  24. * @param $url
  25. * @param null $data
  26. * @return mixed|null
  27. */
  28. protected function curl($url, $data=null)
  29. {
  30. $curl = curl_init();
  31. curl_setopt($curl, CURLOPT_URL, $url);
  32. curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/json; encoding=utf-8']);
  33. if (!empty($data)) {
  34. curl_setopt($curl, CURLOPT_POST, 1);
  35. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  36. }
  37. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  38. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  39. curl_setopt($curl, CURLOPT_HEADER, false);
  40. $data = curl_exec($curl);
  41. curl_close($curl);
  42. return $data;
  43. }
  44. /**
  45. * H5授权,code换accesstoken
  46. */
  47. public function getAccessTokenByCode($appid, $secret, $code)
  48. {
  49. $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
  50. $res = $this->curl($url);
  51. // 返回获取结果
  52. return json_decode($res, true);
  53. }
  54. /**
  55. * H5跳转获取code
  56. */
  57. public function redirectForCode($appid, $redirectUrl)
  58. {
  59. $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($redirectUrl) . '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
  60. header('location:' . $url);
  61. exit;
  62. }
  63. }