微信小程序 - 獲取用戶 openid

在小程序中獲取用戶 openid 基本上是小程序開發面對的第一個問題,在這裏分享下獲取用戶 openid 的簡單例子。html

基本流程:

一、經過登陸調用接口 wx.login  獲取臨時登陸憑證 code ,並回傳到開發者服務器 。java

二、後臺使用 code、appid、appsecret 換取用戶惟一標識 openid 和會話密鑰 session_key。 (appid、appsecret 這2個值在開通微信公衆號認證以後,能夠在微信公衆平臺小程序後臺獲取)json

剛開始進入小程序調用登陸接口,不過如今小程序獲取用戶信息做出調整,若是登陸用到此接口,須要開發者對登陸作出調整參考獲取用戶信息接口調整 ,這裏根據本身業務需求判斷調用該接口,涉及到後臺須要 iv 和 encryptedData 等解密用戶信息等。小程序

直接上代碼:api

App({
  onLaunch: function() {
    wx.login({
      success: function(res) {
        if (res.code) {
          //發起網絡請求
          wx.request({
            url: 'https://xxx/getOpenid',
            data: {
              code: res.code
            }
          })
        } else {
          console.log('登陸失敗!' + res.errMsg)
        }
      }
    });
  }
})

後臺簡單使用 java服務器

@Controller
@RequestMapping("/xxx")
public class GetOpenidController {

	@Autowired
	private TransferService transferService;

	@RequestMapping(value = "/getOpenid")
	public void getOpenid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=UTF-8");
		//這 2 個值在開通公衆號認證以後,能夠在微信後臺獲取
		String APPID = "xxx"; //小程序惟一標識
		String SECRET = "xxx"; //小程序的 app secret
		String code = req.getParameter("code");

		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
		HttpUtil httpUtil = new HttpUtil();
		String openid = "";
		Map<String, String> map = new HashMap<String, String>();
		try {
			HttpResult httpResult = httpUtil.doGet(url, null, null);
			if (httpResult.getStatusCode() == 200) {
				com.google.gson.JsonParser jsonParser = new com.google.gson.JsonParser();
				JsonObject obj = (JsonObject) jsonParser.parse(httpResult.getBody());
				openid = obj.get("openid").getAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (openid != "") {
			map.put("openid", openid);
			transferService.login(map); //保存用戶信息
		}
	}
}

獲取結果除了 openid 還有 session_key,可是切記獲取會話密鑰 session_key 能夠保存在服務器或者用來解密信息。爲了數據不被篡改,開發者不該該把 session_key 傳到小程序客戶端等服務器外的環境。微信

參考以上這個例子就能夠獲取用戶 openid,代碼寫的有點 low 示例僅提供一個思路,具體的實現須要開發者根據本身項目來定。網絡

 

水平有限,如有問題請留言交流!session

互相學習,共同進步 :) 轉載請註明出處謝謝!app

相關文章
相關標籤/搜索