準備資料: 在開放平臺申請網站應用,須要付費300rmb, 臉上笑嘻嘻,內心。。。php
1 第一種模式,在微信做用域執行 css
$redirect_uri="http://你的微信開放平臺綁定域名下處理掃碼事件的方法"; $redirect_uri=urlencode($redirect_uri);//該回調須要url編碼 $appID="你的appid"; $scope="snsapi_login";//寫死,微信暫時只支持這個值 //準備向微信發請求 $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri ."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect"; //請求返回的結果(其實是個html的字符串) $result = file_get_contents($url); //替換圖片的src才能顯示二維碼 $result = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $result); return $result; //返回頁面
點擊這個就會出現這個頁面html
2 第二種模式,內嵌js執行java
引入jsjquery
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/jquery.min.js"></script> <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
html 部分json
<div id="wx_login_container"></div>
js實例api
<script> $(document).ready(function() { var obj = new WxLogin({ self_redirect: true, id:"wx_login_container", appid: "appid", scope: "snsapi_login", redirect_uri: "回調地址", state: "", style: "black", href: "", //https://某個域名下的css文件 }); }); </script>
注意其中href裏指向的css文件必須放在https協議下才能引用的到,大致上不需改變默認樣式,浪費腦細胞,能夠針對div 來改變二維碼的大小和位置,裏邊是內嵌一個iframe微信
效果就是這樣的,下邊兩個手機登錄和當即註冊是我本身加上的,不用理會, app
php 回調代碼:
/** * todo: 微信掃碼登錄回調 * author: 依然範兒特西 * date: 2019-04-27 */ public function wxlogin_notice(){ $code = $_GET["code"]; $appid = Config::get("config_wechat.open_account.default.app_id"); $secret = Config::get("config_wechat.open_account.default.app_script"); if (!empty($code)){ //經過code得到 access_token + openid $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid. "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code"; $jsonResult = file_get_contents($url); $resultArray = json_decode($jsonResult, true); $access_token = $resultArray["access_token"]; $openid = $resultArray["openid"]; //經過access_token + openid 得到用戶全部信息,結果所有存儲在$infoArray裏,後面再寫本身的代碼邏輯 $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid; $infoResult = file_get_contents($infoUrl); $infoArray = json_decode($infoResult, true); //執行登陸,如下代碼要根據本身的業務修改邏輯, $nickname = $infoArray['nickname']; $head_img = $infoArray['headimgurl']; $unionid = $infoArray['unionid']; $user_modle = model("UserModel"); $login_result = $user_modle->wxlogin_qrcode($openid,$nickname,$head_img,$unionid); if($login_result){ echo '<script language="javascript">window.top.location.href="/ucenter/user"</script>'; } } }
建議使用第二種內嵌js ,用戶體驗比較好! over