本文目录一览:
怎么使用 Java SDK
1、在你的Java工程中添加该SDK中dist目录下的jar库,并添加到你的编译路径中。
2、在你的代码中import相应的包名。
3、非web应用请修改和查阅MainDemo.java,web应用请修改config.jsp,查阅index.jsp, 获得包括oauth登录请求及其它功能请求的方法接口。
4、commons包里面的java类实现了目前腾讯微博开发平台的所有接口,除第一个参数是oauth对象外。
其他都和开发平台的api文档一致,类名和方法名亦和api一致。
比如获取主页时间线的api是:
那么此SDK的java类是:Statuses_API.java,实现方法是home_timeline(a,b,c,d...)
5、此SDK为半原创,思路和部分方法函数参考了官方(热心网友sampan)提供的java SDK() 和网上相关的Oauth授权资料
6、javawind-qweibo-api-1.0.jar为本sdk生成的jar。
如果有修改源码,记得重新生成此jar。
如何使用微信sdk java版
1.首先我们新建一个Java开发包WeiXinSDK
2.包路径:com.ansitech.weixin.sdk
测试的前提条件:
假如我的公众账号微信号为:vzhanqun
我的服务器地址为:
下面我们需要新建一个URL的请求地址
我们新建一个Servlet来验证URL的真实性,具体接口参考
接入指南
3.新建com.ansitech.weixin.sdk.WeixinUrlFilter.java
这里我们主要是获取微信服务器法师的验证信息,具体验证代码如下
[java] view plain copy print?
package com.ansitech.weixin.sdk;
import com.ansitech.weixin.sdk.util.SHA1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WeixinUrlFilter implements Filter {
//这个Token是给微信开发者接入时填的
//可以是任意英文字母或数字,长度为3-32字符
private static String Token = "vzhanqun1234567890";
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("WeixinUrlFilter启动成功!");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//微信服务器将发送GET请求到填写的URL上,这里需要判定是否为GET请求
boolean isGet = request.getMethod().toLowerCase().equals("get");
System.out.println("获得微信请求:" + request.getMethod() + " 方式");
if (isGet) {
//验证URL真实性
String signature = request.getParameter("signature");// 微信加密签名
String timestamp = request.getParameter("timestamp");// 时间戳
String nonce = request.getParameter("nonce");// 随机数
String echostr = request.getParameter("echostr");//随机字符串
ListString params = new ArrayListString();
params.add(Token);
params.add(timestamp);
params.add(nonce);
//1. 将token、timestamp、nonce三个参数进行字典序排序
Collections.sort(params, new ComparatorString() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
//2. 将三个参数字符串拼接成一个字符串进行sha1加密
String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
if (temp.equals(signature)) {
response.getWriter().write(echostr);
}
} else {
//处理接收消息
}
}
@Override
public void destroy() {
}
}
好了,不过这里有个SHA1算法,我这里也把SHA1算法的源码给贴出来吧!
4.新建com.ansitech.weixin.sdk.util.SHA1.java
[java] view plain copy print?
/*
* 微信公众平台(JAVA) SDK
*
* Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ansitech.weixin.sdk.util;
import java.security.MessageDigest;
/**
* pTitle: SHA1算法/p
*
* @author qsyangyangqisheng274@163.com
*/
public final class SHA1 {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j len; j++) {
buf.append(HEX_DIGITS[(bytes[j] 4) 0x0f]);
buf.append(HEX_DIGITS[bytes[j] 0x0f]);
}
return buf.toString();
}
public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
5.把这个Servlet配置到web.xml中
[html] view plain copy print?
filter
description微信消息接入接口/description
filter-nameWeixinUrlFilter/filter-name
filter-classcom.ansitech.weixin.sdk.WeixinUrlFilter/filter-class
/filter
filter-mapping
filter-nameWeixinUrlFilter/filter-name
url-pattern/api/vzhanqun/url-pattern
/filter-mapping
好了,接入的开发代码已经完成。
6.下面就把地址URL和密钥Token填入到微信申请成为开发者模式中吧。
怎么用java调用微信支付接口
1.调用微信接口授权
授权这里有两种方式,一种是snsapi_bases,另一种是snsapi_userinfo,这里官方文档介绍的比较清楚,可以参考官网
;t=resource/res_listverify=1id=open1419316505token=lang=zh_CN
appid 登录微信公众号-基本配置-开发者ID-APPID
redirect_uri 就是一个回调地址,当你调用完微信的这个链接后,他会自动调用你定义的这个地址,返回code参数
注意,redirect_uri 也需要在公众号里面配置,在接口权限-网页帐号里修改。
2.可以在页面中写一个调用授权的页面
%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%
!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%
html
head
title用户管理/title
script type="text/javascript" src="js/jquery/jquery-1.11.1.min.js"/script
script type="text/javascript"
function oauth() {
var url = "%=basePath%getOauth2Url";
$.ajax({
url: url,
success : function(result){
//var result = eval('('+result+')');
if (result.success){
location.href = result.obj; //
} else {
}
}
});
}
/script
/head
body
p onclick="oauth()"非用户认证鉴权/p
/body
/html
/prepre class="html" name="code" snippet_file_name="blog_20160608_3_8825275" code_snippet_id="1711669"java中的方法
pre class="html" name="code" /**
* 获取授权地址
* @return
*/
@RequestMapping(value = "/getOauth2Url",method = RequestMethod.GET)
public void getOauth2Url(Model model, HttpServletResponse response) {
Json j = new Json();
try {
String authorize_url = PayConfig.AUTHORIZE_URL;
String appId = PayConfig.APPID;
String redirect_uri = PayConfig.REDIRECT_URI;
String url = authorize_url + "?appid=" + appId + "redirect_uri=" + urlEncodeUTF8(redirect_uri) + "response_type=codescope=snsapi_basestate=STATE#wechat_redirect";
System.out.println(url);
j.setSuccess(true);
j.setMsg("保存成功!");
j.setObj(url);
write(response, JSON.toJSONString(j));
} catch (Exception e) {
j.setMsg(e.getMessage());
}
}
/**
* 对回调地址进行encode
* @param source
* @return
*/
public static String urlEncodeUTF8(String source){
String result = source;
try {
result = java.net.URLEncoder.encode(source,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
pre class="html" name="code" /**
* 获取授权地址
* @return
*/
@RequestMapping(value = "/getOauth2Url",method = RequestMethod.GET)
public void getOauth2Url(Model model, HttpServletResponse response) {
Json j = new Json();
try {
String authorize_url = PayConfig.AUTHORIZE_URL;
String appId = PayConfig.APPID;
String redirect_uri = PayConfig.REDIRECT_URI;
String url = authorize_url + "?appid=" + appId + "redirect_uri=" + urlEncodeUTF8(redirect_uri) + "response_type=codescope=snsapi_basestate=STATE#wechat_redirect";
System.out.println(url);
j.setSuccess(true);
j.setMsg("保存成功!");
j.setObj(url);
write(response, JSON.toJSONString(j));
} catch (Exception e) {
j.setMsg(e.getMessage());
}
}
/**
* 对回调地址进行encode
* @param source
* @return
*/
public static String urlEncodeUTF8(String source){
String result = source;
try {
result = java.net.URLEncoder.encode(source,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
package com.crm.common;
public class PayConfig {
public static String APPID = "wx91af774aae000dcb"; //APPID
public static String MCHID = "1347742701"; //商户编号
public static String PAYKEY = "kong6a9829e4b49a0d2347b4162da6b7"; //支付密钥
public static String APPSECRET = "f8e1ff34070a94332b3b128232acb5abf "; //公众号-基本配置-APPSECRET密钥
public static String REDIRECT_URI = "
回调地址
public static String AUTHORIZE_URL = "
微信授权地址
public static String ACCESS_TOKEN_URI = "
public static String SCOPE = "snsapi_base"; //snsapi_base和snsapi_userinfo
public static String GRANT_TYPE = "grant_type"; //获取openid时用,不用改
}
3.成功后,回到你当时写的回调地址
pre class="html" name="code"/**
* 微信授权后的回调地址的方法
* @param code
* @param response
*/
@RequestMapping(value = "/authorize",method = RequestMethod.GET)
public void authorize(String code, HttpServletResponse response, String openid) {
code = "test";
String access_token_uri = PayConfig.ACCESS_TOKEN_URI;
String appid = PayConfig.APPID;
String secret = PayConfig.APPSECRET;
access_token_uri = access_token_uri.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
System.out.println(access_token_uri);
if(openid != null){
UniteOrder order = getUniteOrder(openid);
String reqXML = PayImpl.generateXML(order, PayConfig.PAYKEY);
String respXML = PayImpl.requestWechat(ORDER_URL, reqXML);
System.out.println("respXML=" + respXML);
UniteOrderResult result = (UniteOrderResult) PayImpl.turnObject(UniteOrderResult.class, respXML);
getWechatPay(result);
}
}