MiniAppService.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace app\utils\Easywechat;
  3. use app\utils\CurlUtil;
  4. /**
  5. * Author:Panda
  6. * Email:joeyoung0314@qq.com
  7. * Class MiniAppService
  8. * @package App\Service\Easywechat
  9. */
  10. class MiniAppService
  11. {
  12. private $config;
  13. private $domain = 'https://api.weixin.qq.com';// 微信接口地址前缀
  14. public function __construct()
  15. {
  16. $this->config = config('user_wxMiniProgram');
  17. }
  18. /**
  19. * 获取openid && session_key
  20. * @param string $code
  21. * @return mixed
  22. */
  23. public function login(string $code)
  24. {
  25. $config = $this->config;
  26. $response = $this->get('/sns/jscode2session', [
  27. 'appid' => $config['appid'],
  28. 'secret' => $config['secret'],
  29. 'js_code' => $code,
  30. 'grant_type' => 'authorization_code',
  31. ]);
  32. return $this->json($response);
  33. }
  34. /**
  35. * 获取手机号
  36. * @param string $code
  37. * @return false|mixed
  38. */
  39. public function getUserPhone(string $code)
  40. {
  41. $access_token = $this->accessToken();
  42. if (empty($access_token['access_token'])){
  43. return $access_token;
  44. }
  45. $response = $this->postJson("/wxa/business/getuserphonenumber?access_token={$access_token['access_token']}", [
  46. 'code' => $code
  47. ]);
  48. return $this->json($response);
  49. }
  50. /**
  51. * 获取 access_token
  52. * @return false|mixed
  53. */
  54. private function accessToken()
  55. {
  56. $config = $this->config;
  57. $response = $this->postJson('/cgi-bin/stable_token', [
  58. 'grant_type' => 'client_credential',
  59. 'appid' => $config['appid'],
  60. 'secret' => $config['secret'],
  61. 'force_refresh' => false,// 默认false:普通模式false;强制刷新模式true;
  62. ]);
  63. return $this->json($response);
  64. }
  65. public function json($response)
  66. {
  67. return json_decode($response, true);
  68. }
  69. private function postJson(string $uri,array $params = []){
  70. return CurlUtil::post($this->domain.$uri,json_encode($params));
  71. }
  72. private function get(string $uri,array $params = []){
  73. return CurlUtil::get($this->domain.$uri,$params);
  74. }
  75. }