欧美三级国产三级日韩三级_亚洲熟妇丰满大屁股熟妇_欧美亚洲成人一区二区三区_国产精品久久久久久模特

Java 后端 (Spring boot)+微信小程序的授權(quán)登錄 - 新聞資訊 - 云南小程序開發(fā)|云南軟件開發(fā)|云南網(wǎng)站建設(shè)-昆明葵宇信息科技有限公司

159-8711-8523

云南網(wǎng)建設(shè)/小程序開發(fā)/軟件開發(fā)

知識

不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價值,我們在追求其視覺表現(xiàn)的同時,更側(cè)重于功能的便捷,營銷的便利,運營的高效,讓網(wǎng)站成為營銷工具,讓軟件能切實提升企業(yè)內(nèi)部管理水平和效率。優(yōu)秀的程序為后期升級提供便捷的支持!

您當前位置>首頁 » 新聞資訊 » 小程序相關(guān) >

Java 后端 (Spring boot)+微信小程序的授權(quán)登錄

發(fā)表時間:2021-1-5

發(fā)布人:葵宇科技

瀏覽次數(shù):199


微信小程序的授權(quán)登錄

第一、Java后端代碼如下 登錄的接口的參數(shù)是微信小程序前端必須要傳的參數(shù)

微信小程序登錄、授權(quán)的用戶基本信息 wx.getUserInfo

特別注意 appid 和secret、grant_type是小程序固定的;可以參考wx.login
param.add(“appid”, “wx367d7fb4108a5162”);
param.add(“secret”, “a700cf3aab35e53e98be18f96ddb4ed9”);
param.add(“js_code”, code);
param.add(“grant_type”, “authorization_code”);

 @Autowired
    private UserService userService;

    /**
     * 微信授權(quán)(登錄)
     * @param code 狀態(tài)碼
     * @param rawData 原始數(shù)據(jù)
     * @return
     */
    @PostMapping("/wxLogin")
    public Result wxLogin(@RequestParam(value = "code", required = false) String code,
                          @RequestParam(value = "rawData", required = false) String rawData,
                          @RequestParam(value = "signature",required = false) String signature) {
//		登錄憑證校驗。通過 wx.login 接口獲得臨時登錄憑證 code 后傳到開發(fā)者服務(wù)器調(diào)用此接口完成登錄流程
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        param.add("appid", "wx367d7fb4108a5162");
        param.add("secret", "a700cf3aab35e53e98be18f96ddb4ed9");
        param.add("js_code", code);
        param.add("grant_type", "authorization_code");
        //RestTemplate 的請求URL;
        // 開發(fā)者服務(wù)器 登錄憑證校驗接口 appi + appsecret + code
        JSONObject forObject = RestTemplateUtil.doPost(url,param);
        System.out.println(forObject);
        //接收微信接口服務(wù) 獲取返回的參數(shù)
        String openid = forObject.getString("openid");
        String sessionKey = forObject.getString("session_key");
        //校驗簽名 小程序發(fā)送的簽名signature與服務(wù)器端生成的簽名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hreex(rawData + sessionKey);
        System.out.println(signature2);
        if (!signature.equals(signature2)) {
            return ResultUtil.error(500, "簽名校驗失敗");
        }
        // 用戶非敏感信息:rawData
        JSONObject rawDataJson = JSONObject.parseObject(rawData);
        //判斷用戶是否存在
        User selectone = userService.Selectone(openid);
        Integer userID=null;
        if (selectone==null){
            // 用戶信息入庫
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            Integer gender = Integer.valueOf(rawDataJson.getString("gender"));
            //添加用戶的信息
            User user=new User();
            user.setOpenid(openid);
            user.setUser_name(nickName);
            user.setUser_gender(gender);
            user.setUser_image(avatarUrl);
            this.userService.save(user);
            userID=user.getUser_id();
        }else {
            userID=selectone.getUser_id();
        }
        return ResultUtil.success(userID);

    }

其中的RestTemplateUtil工具類

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class RestTemplateUtil {
    /**
     * post請求
     * @param url
     * @param param
     * @return
     */
    public static JSONObject doPost(String url, MultiValueMap<String, Object> param){
        RestTemplate restTemplate=new RestTemplate();
        String s = restTemplate.postForObject(url, param, String.class);
        return JSONObject.parseObject(s);
    }
}

第二、微信小程序的簡單授權(quán)代碼

1.login.wxml

<!--pages/login/login.wxml-->
<view wx:if="{{isHide}}">
    <view wx:if="{{canIUse}}" >
        <view class='header'>
            <image src='../images/index.jpg'></image>
        </view>
 
        <view class='content'>
            <view>申請獲取以下權(quán)限</view>
            <text>獲得你的公開信息(昵稱,頭像等)</text>
        </view>

        <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo">
            授權(quán)登錄
        </button>
    </view>
    <view wx:else>請升級微信版本</view>
</view>
 
<view wx:else>
    <view>我的首頁內(nèi)容</view>
</view>

2、login.js

Page({

  /**
   * 頁面的初始數(shù)據(jù)
   */
  data: {
       //判斷小程序的API,回調(diào),參數(shù),組件等是否在當前版本可用。
       canIUse: wx.canIUse('button.open-type.getUserInfo'),
       isHide: false
  },

  /**
   * 生命周期函數(shù)--監(jiān)聽頁面加載
   */
  onLoad: function (options) {
    var that = this;
    // 查看是否授權(quán)
    wx.getSetting({
        success: function(res) {
            if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                    success: function(res) {
                        // 用戶已經(jīng)授權(quán)過,不需要顯示授權(quán)頁面,所以不需要改變 isHide 的值
                        // 根據(jù)自己的需求有其他操作再補充
                        // 我這里實現(xiàn)的是在用戶授權(quán)成功后,調(diào)用微信的 wx.login 接口,從而獲取code
                        console.log(res.signature);
                        console.log(res.rawData);
                        
                        wx.login({
                            success: res => {
                                // 獲取到用戶的 code 之后:res.code
                                console.log("用戶的code:" + res.code);
                                // 可以傳給后臺,再經(jīng)過解析獲取用戶的 openid
                                // 或者可以直接使用微信的提供的接口直接獲取 openid ,方法如下:
                                // wx.request({
                                //     // 自行補上自己的 APPID 和 SECRET
                                //     url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
                                //     success: res => {
                                //         // 獲取到用戶的 openid
                                //         console.log("用戶的openid:" + res.data.openid);
                                //     }
                                // });
                                wx.request({
                                    url: 'http://localhost:2056/user/wxLogin',
                                    method: 'POST',
                                    header: {
                                    'content-type': 'application/x-www-form-urlencoded'
                                    },
                                    data: {
                                        code: res.code, //臨時登錄憑證
                                        rawData: res.rawData, //用戶非敏感信息
                                        signature: res.signature, //簽名
                                    },
                                    success: function(res) {
                                        if (res.data.status == 200) {
                                            // 7.小程序存儲skey(自定義登錄狀態(tài))到本地
                                            wx.setStorageSync('userInfo', userInfo);
                                            wx.setStorageSync('skey', res.data.data);
                                        } else{
                                            console.log('服務(wù)器異常');
                                        }
                                    }
                                })
                                
                            }
                        });
                    }
                });
            } else {
                // 用戶沒有授權(quán)
                // 改變 isHide 的值,顯示授權(quán)頁面
                that.setData({
                    isHide: true
                });
            }
        }
    });
  },

  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
        //用戶按了允許授權(quán)按鈕
        var that = this;
        // 獲取到用戶的信息了,打印到控制臺上看下
        console.log("用戶的信息如下:");
        console.log(e.detail.userInfo); 
        //授權(quán)成功后,通過改變 isHide 的值,讓實現(xiàn)頁面顯示出來,把授權(quán)頁面隱藏起來
        that.setData({
            isHide: false
        });
    } else {
        //用戶按了拒絕按鈕
        wx.showModal({
            title: '警告',
            content: '您點擊了拒絕授權(quán),將無法進入小程序,請授權(quán)之后再進入!!!',
            showCancel: false,
            confirmText: '返回授權(quán)',
            success: function(res) {
                // 用戶沒有授權(quán)成功,不需要改變 isHide 的值
                if (res.confirm) {
                    console.log('用戶點擊了“返回授權(quán)”');
                }
            }
        });
    }
  }

})


3.樣式 login.wxss

/* pages/login/login.wxss */

.header {
  margin: 90rpx 0 90rpx 50rpx;
  border-bottom: 1px solid #ccc;
  text-align: center;
  width: 650rpx;
  height: 300rpx;
  line-height: 450rpx;
}

.header image {
  width: 200rpx;
  height: 200rpx;
}

.content {
  margin-left: 50rpx;
  margin-bottom: 90rpx;
}

.content text {
  display: block;
  color: #9d9d9d;
  margin-top: 40rpx;
}

.bottom {
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
}

相關(guān)案例查看更多