小程序开发获取openid方式

Controller层代码

package com.tm.ethereum.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tm.ethereum.contants.WebConstants;
import com.tm.ethereum.dao.AnaphylaxisLibDao;
import com.tm.ethereum.dao.DrugInfoDao;
import com.tm.ethereum.dao.HotSearchInfoDao;
import com.tm.ethereum.dao.VaccineNameDao;
import com.tm.ethereum.enums.DrugStatusEnum;
import com.tm.ethereum.model.AnaphylaxisLib;
import com.tm.ethereum.model.DrugInfo;
import com.tm.ethereum.model.HotSearchInfo;
import com.tm.ethereum.model.ResObject;
import com.tm.ethereum.model.VaccineName;
import com.tm.ethereum.util.CommonUtil;
import com.tm.ethereum.util.Constant;
import com.tm.ethereum.util.HttpUtils;

@RestController
public class AppController {
	private static final Logger logger=LoggerFactory.getLogger(AppController.class);
	@GetMapping("/app/getOpenId") // 获取用户信息
	public ResObject<Object> getOpenId(String code) {
		logger.info("getOpenId,code:{}",new Object[]{code});
		ResObject<Object> object = new ResObject<Object>(Constant.Code_SUCCESS, Constant.SUCCESS, null, null);
		String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+ systemInfo.getWxAppid()+"&secret="+systemInfo.getWxSecret()+"&js_code="+code+"&grant_type=authorization_code";
		try {
			if (StringUtils.isBlank(code)) {
				System.out.println("code为空");
			} else {
				/*String requestUrl = WX_URL.replace("APPID", SystemInfo.getWxAppid()).replace("SECRET", SystemInfo.getWxSecret())
						.replace("JSCODE", code).replace("authorization_code", "authorization_code");*/
				logger.info("getOpenId,WX_URL:{}",new Object[]{WX_URL});
				JSONObject jsonObject = CommonUtil.httpsRequest(WX_URL, "GET", null);
				logger.info("getOpenId,response:{}",new Object[]{jsonObject});
				if (jsonObject != null) {
					try {
						object.setResObject(jsonObject);
						// 业务操作
						String openid = jsonObject.getString("openid");
						if(WebConstants.ACCESS_TOKEN==null){
						   JSONObject obj=HttpUtils.drugLibAuth(systemInfo.getDrugLibUrlAuth(), systemInfo.getDrugLibAppid(), systemInfo.getDrugLibSecret());
						   logger.info("getOpenId,drugLibAuth obj:{}",new Object[]{obj});
						   if(obj!=null&&obj.containsKey("access_token")){
							   WebConstants.ACCESS_TOKEN=obj.getString("access_token");
						   }
								   
						}
						jsonObject.put("access_token", WebConstants.ACCESS_TOKEN);
						jsonObject.put("drugQueryUrl",systemInfo.getDrugLibUrlDrugQuery()+ WebConstants.ACCESS_TOKEN);
//						wechatService.selectUserByOpenId(openid, headurl, nickname, sex, country, province, city);
//						return openid;
					} catch (Exception e) {
						logger.info("业务操作失败",e);
					}
				} else {
					logger.info("code:{}。无效",new Object[]{code});
					return new ResObject<Object>(Constant.Code_FAIL, "code无效", null, null);
				}
			}
		} catch (Exception e) {
			return new ResObject<Object>(Constant.Code_FAIL, "登录发生异常", null, null);
		}
		
		return object;
	} 
}

工具类CommonUtil

package com.tm.ethereum.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
 
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
 
import net.sf.json.JSONObject;
 
public class CommonUtil {
	/**
     * 发送https请求
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
 
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
 
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
 
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
 
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            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;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("连接超时");
            ce.printStackTrace();
        } catch (Exception e) {
            System.out.println("请求异常");
            e.printStackTrace();
        }
        return jsonObject;
    }
}

工具类MyX509TrustManager

package com.tm.ethereum.util;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
/**
 * 类名: MyX509TrustManager.java</br> 
 * 描述: 信任管理器</br> 
 * 开发人员:wangl</br>
 * 创建时间: 2018-01-09</br>
 */
public class MyX509TrustManager implements X509TrustManager {
 
    // 检查客户端证书
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
 
    // 检查服务器端证书
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
 
    // 返回受信任的X509证书数组
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

注添加maven依赖是发现alibaba引入的json冲突
可使用一下依赖方式解决
解决方案:

<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
</dependency>
根据引用\[1\]中提供的信息,获取微信小程序的openId需要通过调用微信接口路径"https://api.weixin.qq.com/sns/jscode2session"来实现。在前端代码中,需要使用uni.login()方法获取到code值,然后将code值、小程序的appid、secret以及grant_type等参数传递给该接口进行请求。成功获取openId后,可以使用uni.setStorage()方法将openId存储到本地。 引用\[2\]中提到,在小程序发布阶段,直接在前端暴露appid和appsecret是不安全的,因为经过反编译小程序后,这些信息会被获取到。因此,可以考虑使用云函数来获取openId,以增加安全性。 引用\[3\]中提供了一个示例代码,可以在需要获取openId的地方调用getOpenid()方法。在该方法中,使用wx.cloud.callFunction()方法调用云函数来获取openId,并将其存储到全局变量中。 关于报41002的问题,根据提供的信息,无法确定具体的原因。可能是由于参数传递错误、接口调用频率限制或其他原因导致的。建议检查代码中的参数传递是否正确,并确保接口调用符合微信的限制要求。如果问题仍然存在,可以查阅微信开发文档或联系微信开发者支持获取更详细的帮助。 #### 引用[.reference_title] - *1* [uniapp写微信小程序,获取openId、unionId](https://blog.csdn.net/m0_56597737/article/details/131274674)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [微信小程序获取用户openid](https://blog.csdn.net/m0_51421744/article/details/127756088)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值