微信小程序获取code,然后传给后端

一直在搜索各种资料,但是都没有特别全面的,最终七拼八凑,解决了这个问题

前端代码

wxml

<view class="container">
  <button bindtap="senCode">发送code</button>
</view>

js

// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {},
  senCode(){
     //调用wx.login获取code
     wx.login({
      success: function(res) {
        if (res.code) {  //wx.login获取code。
          console.log(res.code);
          //发起网络请求
          wx.request({
            url: '后端api地址',
            method:'POST',
            //向后端发送的数据
            data: {
              code: res.code    //将code发送到后台服务器。
            },
            header: { 
                   "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
          },
          })
        } else {
          console.log('获取用户登录态失败!' + res.errMsg)
        }
      }
    });
  },
  onLoad() {}
})

注意 --一开始数据一直发送不到后端,各种搜索

添加了method,指定为post,然后添加

header: { 
                   "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
          },

后端代码–只有一个controller

package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
public class SendController {
    @ResponseBody
    @RequestMapping(value = "/send",method = POST)
    public static void getOpenid(@RequestParam(value="code",required=false)String code){

        //微信官方提供获取openid的url
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        //替换appid,appsecret,和code
        String requestUrl = WX_URL.replace("APPID", "").//填写自己的appid
                replace("SECRET", "").replace("JSCODE", code).//填写自己的appsecret,
                replace("authorization_code", "authorization_code");
        //定义json对象
        JSONObject convertvalue=new JSONObject();
        //调用get方法
        String  returnvalue=GET(requestUrl);
        //解析返回值,对象解析成字符串
        convertvalue= (JSONObject) JSON.parse(returnvalue);
        String session_key= (String) convertvalue.get("session_key");
        String openid= (String) convertvalue.get("openid");
        System.out.println(returnvalue);
        System.out.println("openid:"+openid);
        System.out.println("session_key:"+session_key);

    }
    //发起ge请求---生成openid和session_key
    public static String GET(String url) {
        String result="";
        BufferedReader in = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try{
            //构造url对象
            URL realUrl = new URL(url);
            //获取一个对应该URL的URLConnection对象
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            is = conn.getInputStream();
            isr = new InputStreamReader(is);
            in = new BufferedReader(isr);
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }catch (Exception e){
          e.printStackTrace();
            System.out.println("异常出现");
        }
        //关闭资源
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("出现异常");
            }
        }
        return result;
    }

}

注意–如果要通过postman进行测试,注意传的数据格式

在这里插入图片描述
否则会数据插入失败。

经过以上步骤即可成功向后端传入code.

方法,注意请求的方法不同,header里的内容也不一样

header{
'Content-Type': 'application/json' //GET方式是这个
},
header: { 
"Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
}
  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值