Rumah applet WeChat pembangunan WeChat 微信公众号支付(一)如何获取用户openId

微信公众号支付(一)如何获取用户openId

Feb 04, 2017 am 11:36 AM

一、获取apikey,appsecret与商户号

  注册公众号、商户号

二、获取用户的OpenId

  1.设置【授权回调页面域名】

    官方解释:用户在网页授权页同意授权给公众号后,微信会将授权数据传给一个回调页面,回调页面需在此域名下,以确保安全可靠。回调页面域名不支持IP地址。

微信公众号支付(一)如何获取用户openId

  2.用户同意授权

    我是把这个url写在微信菜单下的,当进入这个页面的时候就让用户同意。注意:好像是静默授权的,用户不知道

    1.url:
https://open.weixin.qq.com/connect/oauth/authorize?appid=appid&redirect_uri=url&response_type=code&scope=snsapi_userinfo&state=park#wechat_redirect

    参数:appid:公众号的唯一标识

       redirect_uri:重定向的url,就是授权后要跳转的页面

       scope:应用授权作用域

          snsapi_base:不弹出授权页面,直接跳转,只能获取用户openid

          snsapi_userinfo:弹出授权页面,可通过openid拿到昵称、性别、所在地

       state:重定向后带的参数

    2.用户同意后会产生一个code,只有分钟时间的有效期。

String code = request.getParameter("code")
Salin selepas log masuk

    3.code换openId

/**
 * 常量类
 * @author rory.wu
 *
 */
public class Constants {
 // 第三方用户唯一凭证
 public static String appid = "";
 // 第三方用户唯一凭证密钥
 public static String appsecret = "";
 //商户ID
 public static String mch_id="";
 //获取openId
 public static String oauth_url = "https://api.weixin.qq.com/sns/oauth/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
}
Salin selepas log masuk
/**
 * 通用工具类
 * @author rory.wu
 * @version .
 * @since 年月日
 */
 public class CommonUtil {
 private static Logger log = Logger.getLogger(CommonUtil.class);
 public static JSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {
  JSONObject jsonObject = null;
  try {
  StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
  jsonObject = JSONObject.fromObject(buffer.toString());
  } catch (ConnectException ce) {
  log.error("连接超时:"+ce.getMessage());
  } catch (Exception e) {
  log.error("https请求异常:"+e.getMessage());
  }
  return jsonObject;
 }
  
 private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
  throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
  IOException, ProtocolException, UnsupportedEncodingException {
  URL url = new URL(requestUrl);
  HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
  connection.setDoOutput(true);
  connection.setDoInput(true);
  connection.setUseCaches(false);
  connection.setRequestMethod(requestMethod);
  if (null != output) {
  OutputStream outputStream = connection.getOutputStream();
  outputStream.write(output.getBytes("UTF-"));
  outputStream.close();
  }
  // 从输入流读取返回内容
  InputStream inputStream = connection.getInputStream();
  InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-");
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  String str = null;
  StringBuffer buffer = new StringBuffer();
  while ((str = bufferedReader.readLine()) != null) {
  buffer.append(str);
  }
  bufferedReader.close();
  inputStreamReader.close();
  inputStream.close();
  inputStream = null;
  connection.disconnect();
  return buffer;
 } }
 
   /**
 * 获取用户的openId,并放入session
 * @param code 微信返回的code
 */
 private void setOpenId(String code) {
  session.put("code", code);
  String oauth_url = Constants.oauth_url.replace("APPID", Constants.appid).replace("SECRET", Constants.appsecret).replace("CODE", String.valueOf(session.get("code")));
  log.info("oauth_url:"+oauth_url);
  JSONObject jsonObject = CommonUtil.httpsRequestToJsonObject(oauth_url, "POST", null);
  log.info("jsonObject:"+jsonObject);
  Object errorCode = jsonObject.get("errcode");
  if(errorCode != null) {
  log.info("code不合法");
  }else{
  String openId = jsonObject.getString("openid");
  log.info("openId:"+openId);
  session.put("openId", openId);
  }
 }
oauth_url返回的格式是:
  {
   "access_token":"ACCESS_TOKEN",
   "expires_in":,
 "refresh_token":"REFRESH_TOKEN",
 "openid":"OPENID", "scope":"SCOPE",
 "unionid": "o_bmasdasdsad_sgVthMZOPfL"
 }
Code无效时:
  {
   "errcode":
   ,"errmsg":"invalid code"
 }
Salin selepas log masuk

   

以上内容就是脚本之家的小编给大家分享的微信公众号支付(一)如何获取用户openId,希望大家喜欢。

更多微信公众号支付(一)如何获取用户openId相关文章请关注PHP中文网!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

AI Hentai Generator

AI Hentai Generator

Menjana ai hentai secara percuma.

Alat panas

Notepad++7.3.1

Notepad++7.3.1

Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina

SublimeText3 versi Cina

Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6

Dreamweaver CS6

Alat pembangunan web visual

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)