【微信小程序】通过js_code获取session_key,openid

 ['info' => 'REQUEST_IS_NO_POST']];
const REQUEST_IS_NO_CODE = ['errMsg' => ['info' => 'REQUEST_IS_NO_CODE']];
const APPID= 'wxa87da27f03d47b89';
const SECRET = 'a17449d4cce8efb35506cf8a1d44da99';
const GRANTTYPE = 'authorization_code';

class User extends Controller
{
    private $js_code; //登陆许可凭证
    private $openid;  //唯一标识
    private $session_key;  //会话密钥

//    用户登陆
    public function login()
    {
        if(request()->isPost())
        {
            $this->js_code = input('post.code');
            if($this->js_code != '')
            {
                $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.APPID.'&secret='.SECRET.'&js_code='.$this->js_code.'&grant_type='.GRANTTYPE;
                $html = file_get_contents($url);
                $obj = json_decode($html);
                if(isset($obj->errcode)){
                    // 获取用户信息失败
                    return json($obj);
                }else{
                    // 获取用户信息成功
                    $this->openid = $obj->openid;
                    $this->session_key = $obj->session_key;
                    return json($obj);
                }
            }else
            {
                return json(REQUEST_IS_NO_CODE);
            }
        }
        return json(REQUEST_IS_NO_POST);
    }
}

你可能感兴趣的:(【微信小程序】通过js_code获取session_key,openid)