Laravel框架 微信授权登陆 代码封装

44 篇文章 2 订阅
9 篇文章 0 订阅

1.在 Libraries  里面封装wechatApi   代码如下:

<?php

namespace App\Http\Libraries;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Log;

class WeChatApi
{

    /**
     * 微信登录获AccessToken
     *
     * @param [array] $code 通过code换取Token
     * @return void
     */
    public static function getAccessToken($code)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . config('my.weChatAppId') . '&secret=' .  config('my.weChatAppSecret') . '&code=' . $code . '&grant_type=authorization_code';
        try {
            $client = new Client();
            $res = $client->get($url);
        } catch (RequestException $e) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错,请稍后再试。'
            ];
            return $vdata;
        }
        $body = $res->getBody();
        $getCntents = $body->getContents();
        $cntentsArr = json_decode($getCntents, true);

        if (isset($cntentsArr['errcode'])) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错,请稍后再试。',
            ];
            Log::info('微信登录失败代码:');
            Log::info($cntentsArr);
        } else {
            $vdata = [
                'code' => 20000,
                'data' => $cntentsArr,
            ];
        }

        return $vdata;
    }

    /**
     * 获取用户信息方法
     *
     * @param [string] $access_token 微信Token
     * @param [string] $openid 微信Openid
     * @return void
     */
    public static function getUserInfo($access_token, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid;
        try {
            $client = new Client();
            $res = $client->get($url);
        } catch (RequestException $e) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错,请稍后再试。'
            ];
            return $vdata;
        }


        $body = $res->getBody();
        $getCntents = $body->getContents();
        $cntentsArr = json_decode($getCntents, true);

        if (isset($cntentsArr['errcode'])) {
            $vdata = [
                'code' => 20005,
                'msg' => '微信服务器出错,请稍后再试。',
            ];
            Log::info('微信登录失败代码:');
            Log::info($cntentsArr);
        } else {
            $vdata = [
                'code' => 20000,
                'data' => $cntentsArr,
            ];
        }

        return $vdata;
    }
}

 2.在控制器里写调用方法:

   //微信登录
    public function loginWeChat(Request $request)
    {
        $code = request('code');
        $access_token = WeChatApi::getAccessToken($code);
        log::info($access_token);
        if ($access_token['code'] == 20000) {
            $wxUserInfo = WeChatApi::getUserInfo($access_token['data']['access_token'], $access_token['data']['openid']);
            log::info($wxUserInfo);
//            $vdata = $wxUserInfo;
            if ($wxUserInfo['code'] == 20000) {
                $user = Users::where('wx_unionid', $wxUserInfo['data']['unionid'])->first();
                if ($user) {
                    if (empty($user['wx_openid'])) {
                        $user->wx_openid = $wxUserInfo['data']['openid'];
                    }
                    //登录
                    $vdata = $this->quickLogin($user['id']);
                } else {
                    //注册并登录
                    $user_data = [
                        'nickname' => removeWeChatEmoji($wxUserInfo['data']['nickname']),
                        'wx_unionid' => $wxUserInfo['data']['unionid'],
                        'wx_openid' => $wxUserInfo['data']['openid'],
                        'pic' => $wxUserInfo['data']['headimgurl'],
                        'username' => 'mooby_' . uniqid(),
                    ];

                    $add_user = $this->add($user_data);
                    if ($add_user['code'] == 20000) {
                        $vdata = $this->quickLogin($add_user['data']['id']);
                    } else {
                        $vdata = [
                            'code' => 20005,
                            'msg' => trans('msg.error')
                        ];
                    }
                }
            } else {
                $vdata = $wxUserInfo;
            }
        } else {
            $vdata = $access_token;
        }

        return $vdata;
    }

3.配置公众号后台(js接口安全域名)

4.前端调用授权接口(此方法通用  小程序登陆,网页登陆)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值