PHP获取微信openid(静默式不需要用户同意)!

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Aaroun/article/details/86685840

业务需求

因为需要在用户没有关注公众号的情况下获取用户openid,又不需要用户关注,所以需要静默获取一下用户的openid。前提是你需要在微信内打开。

相关代码

以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面):

public function jump()
    {
        $appid = '你的APPID';
        $secret = '你的secret';
        $code = $_GET['code'];//获取code
        //$state = $_GET['state']; //获取参数
        $weixin =  file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code");//通过code换取网页授权access_token
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组

        $openid = $array['openid'];//输出openid

        if ($openid) {
            //你的业务逻辑
            //跳转
            header('Location:http://www.baidu.com');
        }
    }

    /**
     * 获取用户openid,保存名片用
     * @return [type] [description]
     */
    public function get_openid()
    {
        $state = '';
        $appid = '你的APPID';
        $redirect_uri = urlencode('url');//对url处理,此url为访问上面jump方法的url
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?
    appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=$state#wechat_redirect";
        header('Location:' . $url);
    }



我的理解

首先用户访问你的业务逻辑页面时候,你先跳转到get_openid方法中,获取code,获取完code微信会跳转到你传的redirect_rui,当跳转到jump方法后,再用接收的code去获取用户的openid,然后就是通过你获取的openid去操作一些业务逻辑,处理完之后再跳转到你的业务页面。

猜你喜欢

转载自blog.csdn.net/Aaroun/article/details/86685840