123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- namespace App\Modules\Mini\Services;
- use App\Base\BaseService;
- use App\Exceptions\ClientException;
- use App\Models\User\User;
- use EasyWeChat\Kernel\HttpClient\Response;
- use EasyWeChat\MiniApp\Application;
- use Illuminate\Support\Arr;
- class WechatService extends BaseService
- {
- protected $config;
- /**
- * @param $config
- */
- public function __construct()
- {
- $this->config = config('account.wechat.mini_app');
- }
- public function decryptUserInfo($params)
- {
- $data = $this->wechat()->getUtils()->decryptSession($params['session_key'], $params['iv'], $params['encrypted_data']);
- //{
- // "openId": "oGZUI0egBJY1zhBYw2KhdUfwVJJE",
- // "nickName": "Band",
- // "gender": 1,
- // "language": "zh_CN",
- // "city": "Guangzhou",
- // "province": "Guangdong",
- // "country": "CN",
- // "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0",
- // "unionId": "ocMvos6NjeKLIBqg5Mr9QjxrP1FA",
- // "watermark": {
- // "timestamp": 1477314187,
- // "appid": "wx4f4bc4dec97d474b"
- // }
- //}
- /** @var User $user */
- $user = \Auth::user();
- if (is_null($user)) {
- throw new ClientException("need Authentication");
- }
- $user->name = $data['nickName'];
- $user->extra = array_merge($user->extra, [
- "wechat" => $data,
- ]);
- $user->save();
- }
- public function decryptPhone($params)
- {
- $data = $this->wechat()->getUtils()->decryptSession($params['session_key'], $params['iv'], $params['encrypted_data']);
- logger()->info("decryptPhone", $data);
- /** @var User $user */
- $user = \Auth::user();
- if (is_null($user)) {
- throw new ClientException("need Authentication");
- }
- if ($phone = Arr::get($data, "purePhoneNumber")) {
- $user->phone = $phone;
- $user->save();
- }
- }
- /**
- * @return Application
- */
- private function wechat()
- {
- return new Application($this->config);
- }
- /**
- * @see https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
- */
- public function codeToSession($code)
- {
- $options = [
- 'query' => [
- 'appid' => $this->config['app_id'],
- 'js_code' => $code,
- 'secret' => $this->config['secret'],
- "grant_type" => "authorization_code",
- ],
- ];
- return $this->render($this->wechat()->getClient()->get("/sns/jscode2session", $options));
- }
- /**
- * @param Response $resp
- */
- private function render($resp)
- {
- if ($resp->isFailed()) {
- logger()->error("wechat render failer", [
- "resp" => $resp->getContent(),
- ]);
- throw new ClientException("调用微信接口出错,请稍后再试");
- }
- return json_decode($resp->getContent(), true);
- }
- }
|