通过程序获取SessionKey的代码(转)

<!-- -->
管理提醒: <!-- -->
本帖被 gaolei2016 执行取消精华操作(2009-12-18) <!-- -->
<!-- -->
做TOP开发的人肯定会碰到需要SessionKey才能访问数据的情况,手工去取太麻烦了,回调又需要部署到服务器上,杯具啊!为了解决这些麻烦,我特意写了一个通过程序获取SessionKey的方法,代码如下:

说明:本程序只是方便ISV调试使用,集成二次登录是无法通过审核的,用户不会在你的网站里面输入淘宝的用户名和密码的,就好比你不会在一个山寨网站输入你的银行卡号和密码一样。

Copy code
package com.carver.tool;

import java.net.URLEncoder;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImageInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

/**
 * 登录淘宝网获取授权。
 *
 * @author carver.gu
 * @since 1.0, Nov 11, 2009
 */
public class LoginUtil {

    private static final String ONLINE_CONTAINER = "http://container.open.taobao.com/container?appkey=";
    private static final Pattern P_SESSION = Pattern.compile("top\\_session=(\\w+?)&");

    static {
        Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.SEVERE);
        Logger.getLogger("org.apache.commons.httpclient.HttpMethodBase").setLevel(Level.SEVERE);
    }

    public static void main(String[] args) throws Exception {
        String session = getOnlineSession("app_key", "username", "password");
        System.out.println("session_key: " + session);
    }

    public static String getOnlineSession(String appkey, String uid, String pwd) throws Exception {
        String url = "http://member1.taobao.com/member/mini_login.htm?login_type=3&redirect_url=";
        return getSession(url, ONLINE_CONTAINER, appkey, uid, pwd);
    }

    private static String getSession(String loginUrl, String topUrl, String appkey, String uid,
            String pwd) throws Exception {
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);

        String fullUrl = loginUrl + URLEncoder.encode(topUrl + appkey, "utf-8");
        HtmlPage loginPage = webClient.getPage(fullUrl);
        HtmlForm loginForm = loginPage.getForms().get(0);
        HtmlTextInput uidInput = loginForm.getInputByName("TPL_username");
        uidInput.setValueAttribute(uid);
        HtmlPasswordInput pwdInput = loginForm.getInputByName("TPL_password");
        pwdInput.setValueAttribute(pwd);
        HtmlButton loginButton = loginForm.getButtonByName("");

        HtmlPage loginRsp = null;
        try {
            Page rsp = loginButton.click();
            if (rsp instanceof HtmlPage) {
                loginRsp = (HtmlPage) rsp;
            } else if (rsp instanceof TextPage) {
                TextPage textRsp = (TextPage) rsp;
                return extractSession(textRsp.getContent());
            } else {
                return null;
            }
        } catch (FailingHttpStatusCodeException e) {
            if (e.getStatusCode() == 404) {
                return extractSession(e.getMessage());
            }
        } catch (Exception e) {
        }

        HtmlCheckBoxInput agreeCheck = (HtmlCheckBoxInput) loginRsp.getElementById("agreement");
        if (agreeCheck == null) {
            return extractSession(loginRsp.getWebResponse().getRequestSettings().getUrl().toString());
        } else {
            agreeCheck.click();
        }

        HtmlForm agreeForm = loginRsp.getForms().get(1);
        List<HtmlElement> inputElements = agreeForm.getHtmlElementsByTagName("input");
        HtmlImageInput agreeButton = null;
        for (HtmlElement inputElement : inputElements) {
            if (inputElement instanceof HtmlImageInput) {
                agreeButton = (HtmlImageInput) inputElement;
                break;
            }
        }

        Page agreeRsp = null;
        try {
            agreeRsp = agreeButton.click();
        } catch (FailingHttpStatusCodeException e) {
            if (e.getStatusCode() == 404) {
                return extractSession(e.getMessage());
            }
        } catch (Exception e) {
        }
        return extractSession(agreeRsp.getWebResponse().getRequestSettings().getUrl().toString());
    }

    private static String extractSession(String response) {
        Matcher matcher = P_SESSION.matcher(response);
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            return null;
        }
    }

}


经测试,上面的程序可以获取任何类型的应用(Web,客户端)的SessionKey,ISV们有福了。

上面的程序依赖于HtmlUnit这个工具的所有Jar包,需要的请到 HtmlUnit的官方网站下载。
这样做是方便了用户,但好想违反了TOP的审核规则,这样做估计审核会通不过:
审核规则第二条:“2、应用不允许出现二次登陆、注册入口 ”
http://wiki.open.taobao.com/index.php/%E5%AE%A1%E6%A0%B8%E8%A7%84%E5%88%99
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于微信官方提供的 Java SDK,获取微信小程序用户信息的示例代码: ```java import com.alibaba.fastjson.JSONObject; import com.github.wxpay.sdk.WXPay; import com.github.wxpay.sdk.WXPayConfig; import com.github.wxpay.sdk.WXPayConstants; import com.github.wxpay.sdk.WXPayUtil; import java.util.HashMap; import java.util.Map; public class WechatMiniProgramUserInfo { // 小程序 appId private static final String APP_ID = "your_app_id"; // 小程序 appSecret private static final String APP_SECRET = "your_app_secret"; // 微信支付商户号 private static final String MCH_ID = "your_mch_id"; // 微信支付商户密钥 private static final String KEY = "your_key"; // 微信支付统一下单接口 URL private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; // 微信支付查询订单接口 URL private static final String ORDER_QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery"; /** * 获取程序用户信息 * * @param code 用户登录凭证 code * @return 用户信息 JSON 对象 * @throws Exception */ public static JSONObject getUserInfo(String code) throws Exception { // 发送请求,获取 openid 和 session_key String url = "https://api.weixin.qq.com/sns/jscode2session"; Map<String, String> requestParams = new HashMap<>(); requestParams.put("appid", APP_ID); requestParams.put("secret", APP_SECRET); requestParams.put("js_code", code); requestParams.put("grant_type", "authorization_code"); String response = HttpRequestUtil.doGet(url, requestParams); JSONObject responseJson = JSONObject.parseObject(response); String openid = responseJson.getString("openid"); String sessionKey = responseJson.getString("session_key"); // 解密用户信息 String encryptedData = "your_encrypted_data"; // 用户信息密文,需从小程序获取 String iv = "your_iv"; // 加密算法的初始向量,需从小程序获取 String decryptedData = WechatMiniProgramUtil.decryptData(encryptedData, sessionKey, iv); JSONObject userInfoJson = JSONObject.parseObject(decryptedData); // 封装用户信息 JSONObject result = new JSONObject(); result.put("openid", openid); result.put("nickname", userInfoJson.getString("nickName")); result.put("avatar_url", userInfoJson.getString("avatarUrl")); result.put("gender", userInfoJson.getInteger("gender")); result.put("province", userInfoJson.getString("province")); result.put("city", userInfoJson.getString("city")); result.put("country", userInfoJson.getString("country")); return result; } /** * 微信支付统一下单接口 * * @param openid 用户 openid * @param body 商品描述 * @param outTradeNo 商户订单号 * @param totalFee 订单总金额(单位为分) * @param ip 用户 IP 地址 * @return 预支付交易会话标识 prepay_id * @throws Exception */ public static String unifiedOrder(String openid, String body, String outTradeNo, int totalFee, String ip) throws Exception { WXPayConfig config = new WXPayConfig() { @Override public String getAppID() { return APP_ID; } @Override public String getMchID() { return MCH_ID; } @Override public String getKey() { return KEY; } @Override public InputStream getCertStream() { return null; } @Override public int getHttpConnectTimeoutMs() { return 8000; } @Override public int getHttpReadTimeoutMs() { return 10000; } @Override public IWXPayDomain getWXPayDomain() { return WXPayDomainSimpleImpl.instance(); } }; WXPay wxpay = new WXPay(config, WXPayConstants.SignType.MD5); Map<String, String> data = new HashMap<>(); data.put("openid", openid); data.put("body", body); data.put("out_trade_no", outTradeNo); data.put("total_fee", String.valueOf(totalFee)); data.put("spbill_create_ip", ip); data.put("notify_url", "your_notify_url"); data.put("trade_type", "JSAPI"); Map<String, String> response = wxpay.unifiedOrder(data); String returnCode = response.get("return_code"); String resultCode = response.get("result_code"); if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) { return response.get("prepay_id"); } else { throw new Exception("微信支付统一下单失败:" + response.get("return_msg")); } } /** * 微信支付查询订单接口 * * @param outTradeNo 商户订单号 * @return 订单信息 JSON 对象 * @throws Exception */ public static JSONObject orderQuery(String outTradeNo) throws Exception { WXPayConfig config = new WXPayConfig() { @Override public String getAppID() { return APP_ID; } @Override public String getMchID() { return MCH_ID; } @Override public String getKey() { return KEY; } @Override public InputStream getCertStream() { return null; } @Override public int getHttpConnectTimeoutMs() { return 8000; } @Override public int getHttpReadTimeoutMs() { return 10000; } @Override public IWXPayDomain getWXPayDomain() { return WXPayDomainSimpleImpl.instance(); } }; WXPay wxpay = new WXPay(config, WXPayConstants.SignType.MD5); Map<String, String> data = new HashMap<>(); data.put("out_trade_no", outTradeNo); Map<String, String> response = wxpay.orderQuery(data); String returnCode = response.get("return_code"); String resultCode = response.get("result_code"); if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) { JSONObject result = new JSONObject(); result.put("trade_state", response.get("trade_state")); result.put("total_fee", response.get("total_fee")); result.put("transaction_id", response.get("transaction_id")); return result; } else { throw new Exception("微信支付查询订单失败:" + response.get("return_msg")); } } } ``` 其中,`getUserInfo` 方法用于获取用户信息,需要传入用户登录凭证 `code`、用户信息密文和加密算法的初始向量。`unifiedOrder` 方法用于发起微信支付统一下单,需要传入用户 openid、商品描述、商户订单号、订单总金额和用户 IP 地址。`orderQuery` 方法用于查询微信支付订单信息,需要传入商户订单号。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值