通过code2Session接口获取openId(上)

//导入request请求工具类
import {
        getBaseUrl,
        getWxLogin,
        getUserProfile,
        requestUtil
    } from '../../utils/requestUtil';
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    baseUrl:'',
    cart:[],
    totalPrice:0,
    totalNum:0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const baseUrl = getBaseUrl();
    this.setData({
        // swiperList:result.message,
        baseUrl
    })
  },
  //处理订单支付
  async handleOrderPay(){
    // wx.login({
    //     timeout:5000,
    //   success: (res) => {
    //     console.log(res.code)
    //   },
    // })
    // let res=await getWxLogin();
    // console.log(res.code)

    // wx.getUserProfile({
    //     desc:'获取用户信息',
    //     success:(res)=>{
    //         console.log(res.userInfo.nickName,res.userInfo.avatarUrl)
    //     }
    // })

    // let res2 = await getUserProfile();
    // console.log(res2.userInfo.nickName,res2.userInfo.avatarUrl)

    Promise.all([getWxLogin(),getUserProfile()]).then((res)=>{
        console.log(res[0].code);
        console.log(res[1].userInfo.nickName,res[1].userInfo.avatarUrl)
        let loginParam={
            code:res[0].code,
            nickName:res[1].userInfo.nickName,
            avatarUrl:res[1].userInfo.avatarUrl
        }
        console.log(loginParam)
        wx.setStorageSync('userInfo', res[1].userInfo);
        this.wxlogin(loginParam)
    })
  },
  /**
   * 请求后端获取用户token
   * @param {*} loginParam 
   */
  async wxlogin(loginParam){
      const result=await requestUtil({url:"/user/wxlogin",data:loginParam,method:"post"});
      console.log(result);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("show");
    const address=wx.getStorageSync('address');
    let cart=wx.getStorageSync('cart')||[];
    cart=cart.filter(v=>v.checked);
    let totalPrice=0;
    let totalNum=0;
    cart.forEach(v=>{
            totalPrice+=v.price*v.num;
            totalNum+=v.num;
    })
    this.setData({
        cart,
        totalNum,
        address,
        totalPrice
    })

    //cart设置到缓存中
    wx.setStorageSync('cart', cart);
  },   
})
<!-- 收货地址开始  -->
<view class="receive_address_row">

        <view class="user_info">
         <view class="user_info_item">{{address.provinceName+address.cityName+address.countyName}}</view>
         <view class="user_info_item user_info_detail">{{address.detailInfo}}</view>
         <text class="user_info_item"  decode="{{true}}">{{address.userName}}&nbsp;&nbsp;{{address.telNumber}}</text>
        </view>
</view>
<!-- 收货地址结束  -->

<!-- 购物车清单 开始 -->
<view class="cart_content">
    <view class="cart_main">
        <view class="cart_item" wx:for="{{cart}}" wx:key="id">

            <!-- 商品图片 开始 -->
            <navigator class="cart_img_wrap"  url="/pages/product_detail/index?id={{item.id}}">
                <image src="{{baseUrl+'/image/product/'+item.proPic}}" mode="widthFix"></image>
            </navigator>
            <!-- 商品图片 结束 -->

            <!-- 商品信息 开始 -->
            <view class="cart_info_wrap">
                <navigator url="/pages/product_detail/index?id={{item.id}}">
                    <view class="goods_name">{{item.name}}</view>
                </navigator>
                <view class="goods_price_wrap">
                    <view class="goods_price">{{item.price}}
                    </view>
                    <view class="cart_num_tool">
                        <view class="goods_num">×{{item.num}}</view>
                    </view>
                </view>
            </view>
            <!-- 商品信息 结束 -->
        </view>             
    </view>
</view>
<!-- 购物车清单 结束 -->

<!-- 底部工具栏 开始 -->
<view class="footer_tool">

    <!-- 合计 开始 -->
            <view class="total_price_wrap">
                <view class="total_price">{{totalNum}}件,合计: <text class="total_price_text" decode="{{true}}">{{totalPrice}}</text>
                </view>
            </view>
    <!-- 合计 结束 -->

    <!-- 结算 开始 --> 
    <view class="order_pay_wrap" bindtap="handleOrderPay">
        去付款
    </view>
    <!-- 结算 结束 -->

</view>
<!-- 底部工具栏 结束 -->

//定义请求根路径baseUrl
const baseUrl="http://localhost:8080";

//同时并发请求的次数
let ajaxTimes=0;
/**
 * 返回请求根路径baseUrl
 * 
 */
export const getBaseUrl=()=>{
    return baseUrl;
}

/**
 * wx login封装
 * 
 */
export const getWxLogin=()=>{
    return new Promise((resolve,reject)=>{
        wx.login({
            timeout:5000,
          success: (res) => {
            resolve(res)
          },
          fail:(err)=>{
              reject(err)
          }
        })
    });
}



/**
 * wx getUserProfile封装
 * 
 */
export const getUserProfile=()=>{
    return new Promise((resolve,reject)=>{
        wx.getUserProfile({
            desc:'获取用户信息',
            success: (res) => {
                resolve(res)
              },
              fail:(err)=>{
                  reject(err)
              }
        })
    });
}



/**
 * 
 * @param {后端请求工具类} params 
 */
export const requestUtil=(params)=>{

    var start=new Date().getTime();
    console.log(start)
    
    ajaxTimes++;
    wx.showLoading({
      title: '加载中...',
      mask:true
    })

    //模拟网络延迟加载...
    while(true){
        if(new Date().getTime()-start>1*1000)break;
    }

    return new Promise((resolve,reject)=>{
        wx.request({
            ...params,
            url:baseUrl+params.url, 
            success:(result)=>{
                resolve(result.data)
            },
            fail:(err)=>{
                reject(err)
            },
            complete:()=>{
                ajaxTimes--;
                if(ajaxTimes==0){
                    wx.hideLoading();   //关闭加载图标
                }
            }
        })
    });
}
weixin:
  jscode2sessionUrl: https://api.weixin.qq.com/sns/jscode2session
  appid: APPID
  secret: SECRET
package com.java1234.entity;

import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;

import java.beans.Transient;
import java.io.Serializable;
import java.util.Date;

/**
 * 微信用户信息实体
 * @author java1234_小锋
 * @site www.java1234.com
 * @company 南通小锋网络科技有限公司
 * @create 2022-01-08 15:59
 */
@TableName("t_wxUserInfo")
@Data
public class WxUserInfo implements Serializable {

    private Integer id; // 用户编号

    private String openid; // 用户唯一标识

    private String nickName; // 用户昵称

    private String avatarUrl; // 用户头像图片的 URL

    @JsonSerialize(using=CustomDateTimeSerializer.class)
    private Date registerDate; // 注册日期

    @JsonSerialize(using=CustomDateTimeSerializer.class)
    private Date lastLoginDate; // 最后登录日期

    @TableField(select = false,exist = false)
    private String code; // 微信用户code 前端传来的


}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java1234.mapper.WxUserInfoMapper">


</mapper>
package com.java1234.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.java1234.entity.BigType;
import com.java1234.entity.WxUserInfo;

/**
 * 微信用户Service接口
 * Service接口
 */
public interface IWxUserInfoService extends IService<WxUserInfo> {

}

package com.java1234.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java1234.entity.WxUserInfo;
import com.java1234.mapper.WxUserInfoMapper;
import com.java1234.service.IWxUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 商品大类Service实现类
 */
@Service("wxUserInfoService")
public class IWxUserInfoServiceImpl extends ServiceImpl<WxUserInfoMapper,WxUserInfo> implements IWxUserInfoService {

    @Autowired
    private WxUserInfoMapper wxUserInfoMapper;
}

package com.java1234.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 微信小程序配置文件
 * @author java1234_小锋
 * @site www.java1234.com
 * @company 南通小锋网络科技有限公司
 * @create 2022-01-08 17:56
 */
@Component
@ConfigurationProperties(prefix = "weixin")
@Data
public class WeixinProperties {

    private String jscode2sessionUrl; // 登录凭证校验请求地址

    private String appid; // 小程序 appId

    private String secret; // 小程序 appSecret


}

package com.java1234.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.java1234.entity.BigType;
import com.java1234.entity.WxUserInfo;

/**
 * 商品大类Mapper接口
 */
public interface WxUserInfoMapper extends BaseMapper<WxUserInfo> {
}

package com.java1234.entity;

import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;

import java.beans.Transient;
import java.io.Serializable;
import java.util.Date;

/**
 * 微信用户信息实体
 * @author java1234_小锋
 * @site www.java1234.com
 * @company 南通小锋网络科技有限公司
 * @create 2022-01-08 15:59
 */
@TableName("t_wxUserInfo")
@Data
public class WxUserInfo implements Serializable {

    private Integer id; // 用户编号

    private String openid; // 用户唯一标识

    private String nickName; // 用户昵称

    private String avatarUrl; // 用户头像图片的 URL

    @JsonSerialize(using=CustomDateTimeSerializer.class)
    private Date registerDate; // 注册日期

    @JsonSerialize(using=CustomDateTimeSerializer.class)
    private Date lastLoginDate; // 最后登录日期

    @TableField(select = false,exist = false)
    private String code; // 微信用户code 前端传来的


}

package com.java1234.controller;


import com.java1234.entity.R;
import com.java1234.entity.WxUserInfo;
import com.java1234.properties.WeixinProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private WeixinProperties weixinProperties;

    /**
     * 微信用户登录
     * @return
     */
    @RequestMapping("/wxlogin")
    public R wxLogin(@RequestBody WxUserInfo wxUserInfo){
        System.out.println(wxUserInfo);
        // 通过jscode2session 获取openId
        String jscode2sessionUrl=weixinProperties.getJscode2sessionUrl()+"?appid="+weixinProperties.getAppid()+"&secret="+weixinProperties.getSecret()+"&js_code="+wxUserInfo.getCode()+"&grant_type=authorization_code";
        System.out.println(jscode2sessionUrl);
        return R.ok();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值