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;
-
- 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']);
-
- $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);
-
- $user = \Auth::user();
- if (is_null($user)) {
- throw new ClientException("need Authentication");
- }
- if ($phone = Arr::get($data, "purePhoneNumber")) {
- $user->phone = $phone;
- $user->save();
- }
- }
-
- private function wechat()
- {
- return new Application($this->config);
- }
-
- 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));
- }
-
- private function render($resp)
- {
- if ($resp->isFailed()) {
- logger()->error("wechat render failer", [
- "resp" => $resp->getContent(),
- ]);
- throw new ClientException("调用微信接口出错,请稍后再试");
- }
- return json_decode($resp->getContent(), true);
- }
- }
|