spring boot 利用微信小程序登錄接口完成登錄

0.java web端

public class UserController {
    @Autowired UserService userService;
    @Autowired ObjectMapper objectMapper;
    private  String wxspAppid = "your_Appid";
    //小程序的 app secret (在微信小程序管理后臺獲取)
    private  String wxspSecret = "your_Secret ";
    private String openid;
    private Logger logger = LoggerFactory.getLogger(UserService.class);
    @PostMapping ("/signinUser")
    public User signinUser(@RequestParam String code) throws IOException
    {
        RestTemplate restTemplate = new RestTemplate();// 發(fā)送request請求
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" +code;//參數(shù)
        String url = "https://api.weixin.qq.com/sns/jscode2session?"+params;// 微信接口 用于查詢oponid
        String response = restTemplate.getForObject(url,String.class);
        logger.info("response:"+response);
        WeixinRespense weixinRespense = objectMapper.readValue(response,WeixinRespense.class); // 逆序列化 ,將字符串中的有效信息取出
        String session_key = weixinRespense.getSession_key();//如果解密encryptData獲取unionId,會用的到
        openid= weixinRespense.getOpenid();//微信小程序 用戶唯一標識
        logger.info("session_key:"+session_key);
        logger.info("openid:"+openid);

        // 注冊用戶,將查詢到的oponid作為id
        User user = new User();
        user.setUid(openid);
        user.setBalence(Float.valueOf(0));
        if (userService.existbyid(openid))
        {
            return userService.getUserById(openid);
        }
        else {
            if (userService.signupUser(user) == 1)
            {
                return userService.getUserById(openid);
            }
            else {
                return null;
            }
        }
}

1.微信小程序端

  • wxml

   
 <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo">授權(quán) </button>
  </view>
  • js
const app = getApp()
function getCom()
{
  var url = 'http://39.105.78.64:8081/micromarket/getCommodityList'
  var com = {}
  wx.request({
    url: url,
    data: { page: 0 },
    method: 'GET',
    dataType: 'json',
    success: function (res) {
      com = res;
    },
    fail: function (err) {
      console.log(err)
    }

  })
   page = page + 1
   return com

}
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    commodities:{}
  },
  //事件處理函數(shù)
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    var that = this
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是網(wǎng)絡(luò)請求蚁鳖,可能會在 Page.onLoad 之后才返回
      // 所以此處加入 callback 以防止這種情況
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在沒有 open-type=getUserInfo 版本的兼容處理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    wx.login({
      success: function (r) {
        console.log("code:" + r.code + "\n end")
        if (r.code) {
          app.globalData.code = r.code;//登錄憑證  
          var url = 'http://39.105.78.64:8081/micromarket/signinUser'
          //發(fā)起網(wǎng)絡(luò)請求  
          wx.request({
            url: url,
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: { code: app.globalData.code },
            dataType: 'json',
            success: function (result) {
              app.globalData.user = result.data
              console.log(app.globalData.user)
              console.log(app.globalData.user.balence)
            },
            fail: function () {
              console.log(" post error")
            }
          })
        }
      },
      fail: function () {
        console.log("error")
      }
    })
    commodities: getCom()
  },
  getUserInfo: function (info) {
    console.log(info)
    app.globalData.userInfo = info.detail.userInfo
    this.setData({
      userInfo: info.detail.userInfo,
      hasUserInfo: true
    })
  }
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末莉恼,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖诗茎,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異献汗,居然都是意外死亡错沃,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門雀瓢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人玉掸,你說我怎么就攤上這事刃麸。” “怎么了司浪?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵泊业,是天一觀的道長把沼。 經(jīng)常有香客問我,道長吁伺,這世上最難降的妖魔是什么饮睬? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮篮奄,結(jié)果婚禮上捆愁,老公的妹妹穿的比我還像新娘。我一直安慰自己窟却,他們只是感情好昼丑,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著夸赫,像睡著了一般菩帝。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上茬腿,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天呼奢,我揣著相機與錄音,去河邊找鬼切平。 笑死握础,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的揭绑。 我是一名探鬼主播弓候,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼他匪!你這毒婦竟也來了菇存?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤邦蜜,失蹤者是張志新(化名)和其女友劉穎依鸥,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體悼沈,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡贱迟,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了絮供。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衣吠。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖壤靶,靈堂內(nèi)的尸體忽然破棺而出缚俏,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布忧换,位于F島的核電站恬惯,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏亚茬。R本人自食惡果不足惜酪耳,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望刹缝。 院中可真熱鬧碗暗,春花似錦、人聲如沸赞草。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽厨疙。三九已至洲守,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間沾凄,已是汗流浹背梗醇。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留撒蟀,地道東北人叙谨。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像保屯,于是被迫代替她去往敵國和親手负。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容