WechatService.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace app\common\library\easywechatPlus;
  3. use fast\Http;
  4. use think\Log;
  5. use think\Config;
  6. use app\common\exception\BusinessException;
  7. use app\common\facade\HttpClient;
  8. /**
  9. * 微信服务类 - 继承EasywechatPlus,支持facade配置
  10. */
  11. class WechatService extends EasywechatPlus
  12. {
  13. /**
  14. * 生成小程序码
  15. * @param array $param
  16. * @return string
  17. */
  18. public function getWxCodeUnlimited($param)
  19. {
  20. $access_token = $this->getAccessToken();
  21. $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit';
  22. $data = array_merge([
  23. 'width' => 280
  24. ], $param);
  25. $result = HttpClient::request('post', $url, [
  26. 'body' => json_encode($data, JSON_UNESCAPED_UNICODE),
  27. 'query' => ["access_token" => $access_token['access_token']],
  28. 'headers' => ['Content-Type' => 'application/json']
  29. ]);
  30. $result = $result->getBody()->getContents();
  31. // Log::write('getWxCodeUnlimited:'.$result);
  32. return json_decode($result,true);
  33. }
  34. /**
  35. * 获取手机号
  36. * @param string $code
  37. * @return array
  38. */
  39. public function getWechatMobile($code)
  40. {
  41. $access_token = $this->getAccessToken();
  42. $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
  43. $res = HttpClient::request('post', $url, [
  44. 'body' => json_encode(['code' => $code]),
  45. 'query' => ["access_token" => $access_token['access_token']],
  46. 'headers' => ['Content-Type' => 'application/json']
  47. ]);
  48. $res = $res->getBody()->getContents();
  49. $res = (array)json_decode($res, true);
  50. if (!isset($res['phone_info']) && Config::get('app_debug')) {
  51. Log::write($res, 'get_phone');
  52. }
  53. return $res['phone_info'] ?? [];
  54. }
  55. /**
  56. * 获取Session信息
  57. * @param string $code
  58. * @return array
  59. */
  60. public function getWechatSession($code)
  61. {
  62. $access_token = $this->getAccessToken();
  63. $url = "https://api.weixin.qq.com/sns/jscode2session";
  64. $result = HttpClient::request('get', $url, [
  65. 'query' => [
  66. "access_token" => $access_token['access_token'],
  67. 'appid' => $this->app->app_id,
  68. 'secret' => $this->app->app_secret,
  69. 'js_code' => $code,
  70. 'grant_type' => 'authorization_code'
  71. ],
  72. ]);
  73. $result = $result->getBody()->getContents();
  74. $result = json_decode($result, true);
  75. if ($result['errcode'] == 0) {
  76. return $result;
  77. }
  78. if (Config::get('app_debug')) {
  79. Log::write($result, 'get_session');
  80. }
  81. return ['errmsg' => Config::get('app_debug') ? $result['errmsg'] : '网络错误'];
  82. }
  83. }