小程序怎么获取openid

  • A+
所属分类:PHP
下面以laravel中代码方法示例
/*
     *获取openid
     */
    public function openid(Request $request)
    {

        $appid = $request->input('appid');
        $secret = $request->input('secret','');
        $login_code = $request->input('login_code','');
        $url = "https://api.weixin.qq.com/sns/jscode2session";
         $params = [
            'appid'      => $appid,
            'secret'     => $secret,
            'js_code'    => $login_code,
            'grant_type' => 'authorization_code'
        ];
        $newopenid = new UserController;
        $result = $newopenid->sends($url, $params);
        $result = json_decode($result, true);
        if(isset($result['errcode']))
        {
            $data = [
                    'code'=>0,
                    'msg'=>'获取失败'
            ];
            return json_encode($data);
        }
        $openid = $result['openid'];
        unset($data);
        $data = $result;
        return json_encode($data);
    }

     /**
     * 微信兼容方法
     * @return [type] [description]
     */
    public static function sends($url, $params=array(), $timeout=30)
    {
        if ($params) { 
             $url = $url . '?';
            foreach ($params as $key=>$value) {
                $url = $url . $key . "=" . $value . "&";
            }
            $url = substr($url, 0, -1);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

        if (stripos($url,'https://') === 0) {
            $options[CURLOPT_SSL_VERIFYHOST] = false;
            $options[CURLOPT_SSL_VERIFYPEER] = false;
        }
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

 

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信小程序
  • 我的微信小程序扫一扫
  • weinxin
Lion

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: