微信接口調用,真的是難者不會,會者不難只要做過一遍之后以后再做就很簡單了,當初我一個人因為么有人請教,在這一塊耽誤了好幾天的時間,網上的教程也都搜過,可能因為沒接觸過吧,看的也不是很明白,今天來做一個比較詳細的教程出來,加深一下自己的印象,也希望能幫助一些新手
微信開放平台官方文檔:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
第一步:就是准備工作,要在微信開放平台獲取網站的APPID和AppSecret。
然后在前端頁面寫一個登錄按鈕
第一種:直接調起微信登錄
1、點擊登錄按鈕
這個鏈接會返回兩個參數(code和state)到redirect_uri
2、通過的code和AppID、AppSecret獲取access_token
public function getpson(){
$data = I('get.');
$code = $data['code'];
if(empty($code)){
echo json_encode('code值不能為空!');exit;
}
$appid = C('h5_appid');
$secret = C('h5_secret');
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';(
https://api.weixin.qq.com/sns/oauth2/access_token?appid=你的AppID&secret=你的Appsecret&code=code&grant_type=authorization_code)
$one = httpGet($url);
$one = json_decode($one,true);
}
3、通過access_token和openid獲取用戶的信息(這里說一下openid和unionid的區別,openid是微信開放平台中每一個網站或者APP獨有的,而unionid是整個微信開放平台共享的,所以說如果是多個網站或網站和APP共用用戶信息的話,可以用unionid來儲存用戶信息)
public function getinfo(){
$data = I('post.');
$openid = $data['openid'];
$access_token=$data['access_token'];
$url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$file_contents = httpGet($url);
$file_contents = json_decode($file_contents,true);
echo json_encode($file_contents);exit;
}
https://api.weixin.qq.com/sns/userinfo?access_token=access_token.&openid=openid&lang=zh_CN
返回的是json類型
到這里基本上已經完了,之后就是對用戶信息的操作了。
第二種:掃碼登錄
掃碼登陸和直接調用微信進行登錄的區別只在第一步獲取code的方式不同
直接調用微信登錄是訪問鏈接,掃碼登錄是通過將微信登錄二維碼嵌入到網站頁面中,同樣會返回code。
1、首先引入微信官方提供的js文件
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
然后就是二維碼的樣式
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<div id="ss"><div id="wxCode"></div></div>
<script>
$(document).ready(function(){
var obj = new WxLogin({
id:"wxCode", //div的id
appid: "后台申請的appid",
scope: "snsapi_login", //寫死
redirect_uri:encodeURI("https://www.baidu.com") , //掃描二維碼后跳轉的頁面
state: "state",
style: "black",//二維碼黑白風格
href: ""
});
});
</script>
掃過二維碼之后同樣會返回兩個參數(code和state)到redirect_uri。
后面的步驟就和上面直接調用微信登錄的步驟一樣了