小程序之获取用户openid


说明:

1.小程序调用wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。


2.开发者服务器以code换取 用户唯一标识openid 和 会话密钥session_key。


获取openid的官方接口地址如下:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

appid	 小程序唯一标识
secret	 小程序的 app secret
js_code	 登录时获取的 code
grant_type   填写为 authorization_code

app.js

onLaunch: function () {
    var that = this 
    wx.login({
      success: function (res) {
        //code 获取用户信息的凭证
        if (res.code) {
          //请求获取用户详细信息
          wx.request({
            url: "https://pig.intmote.com/wxApp/user/getOpenid.do",
            data: { "code": res.code },
            method: 'GET',
            header: {
              'Content-type': 'application/json'
            },
            success: function (res) {
              //保存openid
              wx.setStorageSync('openid', res.data.openid);//存储openid
              wx.showToast({ title: "登录成功" })
            }
          });
        } else {
          wx.showToast({ title: "登录失败" })
        }
      }
    }) 
   },


注意:

1:pig.intmote.com需要配置成支持https协议请求

2:小程序后台需要配置服务器域名



服务器代码

maven依赖:

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.3</version>
</dependency>


UserController:

package com.lide.wx;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lide.utils.HttpclientUtil;
import com.lide.utils.WxCommon;

@Controller
@RequestMapping("user")
public class UserController {

	@RequestMapping(value = "getOpenid", method = RequestMethod.GET)
	@ResponseBody
	public String getOpenid(@RequestParam("code") String code) {

		// 定义url
		String reqURL = WxCommon.open_url.replace("APPID", WxCommon.AppId)
				.replace("SECRET", WxCommon.AppSecret).replace("JSCODE", code);

		//执行httpclient请求
		String content = HttpclientUtil.sendGetRequest(reqURL, "UTF-8");

		return content;
	}

}


WxCommon:

package com.lide.utils;

public class WxCommon {
	
	public static String AppId = "wxc5fk17d956b6f943";
	
	public static String AppSecret = "fa59db212e2b7399ab98dada05e7594d";
	
	public static String open_url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

}


HttpclientUtil:

package com.lide.utils;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpclientUtil {
	private static Log logger = LogFactory.getLog(HttpclientUtil.class);

	/**
	 * 发送HTTP_GET请求
	 * 
	 * @see 该方法会自动关闭连接,释放资源
	 * @param requestURL
	 *            请求地址(含参数)
	 * @param decodeCharset
	 *            解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendGetRequest(String reqURL, String decodeCharset) {
		long responseLength = 0; // 响应长度
		String responseContent = null; // 响应内容
		HttpClient httpClient = new DefaultHttpClient(); // 创建默认的httpClient实例
		HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGet
		try {
			HttpResponse response = httpClient.execute(httpGet); // 执行GET请求
			HttpEntity entity = response.getEntity(); // 获取响应实体
			if (null != entity) {
				responseLength = entity.getContentLength();
				responseContent = EntityUtils.toString(entity,
						decodeCharset == null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity); // Consume response content
			}
		} catch (ClientProtocolException e) {
			logger.debug("协议错误异常", e);
		} catch (ParseException e) {
			logger.debug(e.getMessage(), e);
		} catch (IOException e) {
			logger.debug("网络异常", e);
		} finally {
			httpClient.getConnectionManager().shutdown(); // 关闭连接,释放资源
		}
		return responseContent;
	}

}

猜你喜欢

转载自blog.csdn.net/qq_37936542/article/details/80447971