WechatService.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Modules\Mini\Services;
  3. use App\Base\BaseService;
  4. use App\Exceptions\ClientException;
  5. use App\Models\User\User;
  6. use EasyWeChat\Kernel\HttpClient\Response;
  7. use EasyWeChat\MiniApp\Application;
  8. class WechatService extends BaseService
  9. {
  10. protected $config;
  11. /**
  12. * @param $config
  13. */
  14. public function __construct()
  15. {
  16. $this->config = config('account.wechat.mini_app');
  17. }
  18. public function decryptUserInfo($params)
  19. {
  20. $data = $this->wechat()->getUtils()->decryptSession($params['session_key'], $params['iv'], $params['encrypted_data']);
  21. //{
  22. // "openId": "oGZUI0egBJY1zhBYw2KhdUfwVJJE",
  23. // "nickName": "Band",
  24. // "gender": 1,
  25. // "language": "zh_CN",
  26. // "city": "Guangzhou",
  27. // "province": "Guangdong",
  28. // "country": "CN",
  29. // "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0",
  30. // "unionId": "ocMvos6NjeKLIBqg5Mr9QjxrP1FA",
  31. // "watermark": {
  32. // "timestamp": 1477314187,
  33. // "appid": "wx4f4bc4dec97d474b"
  34. // }
  35. //}
  36. /** @var User $user */
  37. $user = \Auth::user();
  38. if (is_null($user)) {
  39. throw new ClientException("need Authentication");
  40. }
  41. $user->name = $data['nickName'];
  42. $user->extra = array_merge($user->extra, [
  43. "wechatdata" => $data,
  44. ]);
  45. $user->save();
  46. }
  47. /**
  48. * @return Application
  49. */
  50. private function wechat()
  51. {
  52. return new Application($this->config);
  53. }
  54. /**
  55. * @see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
  56. */
  57. public function codeToSession($code)
  58. {
  59. $options = [
  60. 'query' => [
  61. 'appid' => $this->config['app_id'],
  62. 'js_code' => $code,
  63. 'secret' => $this->config['secret'],
  64. "grant_type" => "authorization_code",
  65. ],
  66. ];
  67. return $this->render($this->wechat()->getClient()->get("/sns/jscode2session", $options));
  68. }
  69. /**
  70. * @param Response $resp
  71. */
  72. private function render($resp)
  73. {
  74. if ($resp->isFailed()) {
  75. logger()->error("wechat render failer", [
  76. "resp" => $resp->getContent(),
  77. ]);
  78. throw new ClientException("调用微信接口出错,请稍后再试");
  79. }
  80. return json_decode($resp->getContent(), true);
  81. }
  82. }