微信小程序wx.login()獲取openid,附:前端+后端代碼


微信小程序開放了微信登錄的api,無論是個人還是企業申請的小程序均可使用。

首先創建一個項目,把這些代碼都清空,我們自己寫!

clipboard.png

然后,開始寫了!
首先index.wxml,寫一個button用於發起登錄

index.wxml

<!--index.wxml-->
<button bindtap='login'>登錄</button>

然后寫index.js

通過wx.login()來獲取code
如果成功獲取,那么返回code
然后調用wx.request()向服務端發起一個請求,即向登錄api接口發送code
換取openid和session_key

api接口:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code
//index.js
//獲取應用實例
const app = getApp()
Page({
  data: {
    
  },
  //登錄獲取code
  login:function(){
    wx.login({
      success:function(res){
        console.log(res.code)
        //發送請求
        wx.request({
          url: 'test.php', //接口地址
          data: {code:res.code},
          header: {
            'content-type': 'application/json' //默認值
          },
          success: function (res) {
            console.log(res.data)
          }
        })
      }
    })
  }
})

app.js,這個清空,留下這樣就行了

//app.js
App({
 
})

那么到這里,小程序端已經搞定了。
開始寫服務端,也很容易。

首先獲取從小程序傳過來的code
再配置自己小程序的appid和appscret
把這些參數拼接到api接口上進行請求發送就可以返回openid和session_key

<?php
//聲明CODE,獲取小程序傳過來的CODE
$code = $_GET["code"];
//配置appid
$appid = "修改成你小程序的APPID";
//配置appscret
$secret = "修改成你小程序的APPSECRET";
//api接口
$api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
//獲取GET請求
function httpGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
//發送
$str = httpGet($api);
echo $str;
?>

OK完成!把服務端上傳到服務器,換到上面的這里

clipboard.png

然后就可以再控制台打印出openid和session_key了

clipboard.png

獲取到了,你想怎么玩就怎么玩!后面可以通過wx.getUserinfo獲取用戶基本信息(頭像,昵稱,城市,個性簽名等相關信息)

作者:tanking


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM