网站实现 绑定微信号功能【通过二维码带参引导授权,获取openid,然后绑定】

| 阅读:173 发表时间:2019-07-03 16:51:26 微信

核心思路:网站链接带参数生成绑定二维码 ----》用户手机扫码----》微信网页授权-----》获取到openid------》转至网站绑定页面-------》将openid和id绑定入数据库。

第一步:先定义$appid,和$secret,并传入参数

 $id = $_REQUEST['id'];
  if ($code) {
    $result = getWxInfo($appid, $secret, $code, 1);
    $_SESSION['openid'] = $result['openid'];
    $_SESSION['nickname'] = $result['nickname'];
    $openid = $result['openid'];
    $nickname = $result['nickname'];
  } else {
    if($_SESSION['openid']){
        $openid = $_SESSION['openid'];
        $nickname = $_SESSION['nickname'];
    }else{
        getWxCode($appid, 1);
    }
  }

第二步:

if($openid){ //实现绑定入库}

获取微信授权封装方法: 

function getWxCode($appid, $type = false)
    {
        if ($type) {
            $scope = 'snsapi_userinfo';
        } else {
            $scope = 'snsapi_base';
        }
        $url = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        $href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%d#wechat_redirect";
        $href = sprintf($href, $appid, $url, $scope, 123);
        header("Location:".$href);
        exit;
    }


function getWxInfo($appid, $secret, $code, $type=false){
    $result = http_get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code');
    
    $result = json_decode($result, 1);
    if ($type) {
            if ($result['access_token']) {
                $Userinfo = http_get('https://api.weixin.qq.com/sns/userinfo?access_token=' . $result['access_token'] . '&openid=' . $result['openid']);
				$Userinfo = json_decode($Userinfo, 1);
                return $Userinfo;
            }
    } else {
      return $result;
    }
  return false;
}

function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
*文章为作者独立观点,不代表【uuuho有乎】的立场
本文由【uuuho有乎】发表并编辑,转载此文章须经作者同意,并请附上出处及本页链接。如有侵权,请联系本站删除。