PHP 微信三方平台代公众号发起网页授权 获取用户信息

1、获取code

2、通过授权回调地址的code获取用户access_token和open_id

3、通过access_token和open_id 获取用户基本信息

class wx_user
{
    public static function getUserAccessToken($code, $app_id )
    {
        $component_appid = \Yii::$app->params['app_id'];
        $component_access_token = wx_auth::getComponentAccessToken();
        $url = 'https://api.weixin.qq.com/sns/oauth2/component/access_token?appid='.$app_id.'&code='.$code.'&grant_type=authorization_code&component_appid='.$component_appid.'&component_access_token='.$component_access_token;
        return  wx_tools::getCurl($url);

    }
    // 刷新account_token

    // 通过网页授权access_token获取用户基本信息

    public static function getUserInfo($access_token, $openid)
    {

        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        return wx_tools::getCurl($url);
    }
}

 

action请求

 /**
     *用户授权
     * @return \yii\web\Response
     */
    public function actionAuthUser()
    {
        $request = \Yii::$app->request;
        $app_id =\Yii::$app->params['hywx_test']['app_id'];
        $redirect_uri = \Yii::$app->request->hostInfo . \Yii::$app->request->scriptUrl . '/wx-auth/user-redirect';
        $component_appid = \Yii::$app->params['app_id'];
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $app_id . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_base&state=STATE&component_appid=' . $component_appid . '#wechat_redirect';
        return $this->redirect($url);
    }

    /**
     * 用户授权回调地址
     */
    public function actionUserRedirect()
    {
        $request = \Yii::$app->request;
        $code = $request->get('code');
        $state = explode(',', $request->get('state'));
        $league_id = $state[0];
        $type = $state[1];
        $app_id = $request->get('appid');
        $res = json_decode(wx_user::getUserAccessToken($code, $app_id));
        $userInfo = wx_user::getUserInfo($res->access_token, $res->openid);
        $item = json_decode($userInfo);
    }
posted @ 2020-05-19 10:27  鲜花满月楼  阅读(633)  评论(0编辑  收藏  举报