微信ウィジェットのドッキングに主に関連するインタフェース(参考のみ)
28666 ワード
1. openid session_key
/**
* @Description: openid session_key
*/
@PostMapping("/getOpenId")
public Map getOpenId(String code){
Map map = new HashMap<>();
//
if (null == code || code.length() == 0){
map.put("errMessage","code !");
return map;
}
//1. code session_key openid
//
Map params = new HashMap<>();
params.put("appid",StringInfo.APPID);
params.put("secret",StringInfo.APPSECRET);
params.put("js_code",code);
params.put("grant_type","authorization_code");
String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session?",params);
JSONObject json = JSON.parseObject(result);
System.out.println(json);
if (json != null) {
//
if (json.getString("errcode")==null) {
map.put("openid",json.getString("openid"));//
map.put("sessionKey",json.getString("session_key"));//
if (json.getString("unionid") != null) {
map.put("unionid", json.getString("unionid"));//
}
}else{
// ,
map.put("errMessage",json.getString("errmsg"));
}
}
System.out.println(JSON.toJSON(map));
return map;
}
2.アクセスポイントの取得
/**
* @Description: AccessToken
*/
@PostMapping("/getAccessToken")
public Map getAccessToken(){
Map map = new HashMap<>();
Map params = new HashMap<>();
//
params.put("grant_type","client_credential");
params.put("appid", StringInfo.APPID);
params.put("secret",StringInfo.APPSECRET);
//
String result = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?",params);
// json
JSONObject json = JSON.parseObject(result);
if (json != null) {
if (json.getString("errcode") == null){
map.put("accessToken",json.getString("access_token"));
map.put("expiresIn",json.getString("expires_in"));
}else {
map.put("errMessage",json.getString("errmsg"));
}
}
return map;
}
3.微信支払
/**
*
* @param openid
* @param body1
* @param total_fee1
* @return
*/
@RequestMapping("/WeiXinPay")
public @ResponseBody Object WeiXinPay(String openid,String body1,int total_fee1
) {
try {
String appid = userService.getUser().getAppid(); // --》“ ID”
String mch_id = userService.getUser().getMchId(); // , partner
String key = userService.getUser().getMchKey(); // )--》“API ”--》“API ”--“ ”( partnerkey,32 )
LOGGER.debug(appid);
LOGGER.debug(mch_id);
LOGGER.debug(key);
String body = body1; //
int total_fee = total_fee1; //
Date data = new Date();
String notify_url = "https://www.baidu.com/weixinpay/notify"; // ,
String out_trade_no = IdUtils.genOrderName();//IdUtils-->
LOGGER.debug(out_trade_no);
Map
6.微信返金
/**
*
* @param request
* @param database
* @param out_trade_no
* @param all_total_fee
* @param refund_fee
* @return
*/
@RequestMapping("/WeiXinRefund")
public @ResponseBody Object WeiXinRefund(HttpServletRequest request,
@RequestParam("out_trade_no") String out_trade_no,
@RequestParam("all_total_fee") int all_total_fee,
@RequestParam("refund_fee") int refund_fee) {
try {
LOGGER.debug(" --->"+out_trade_no);
LOGGER.debug(" --->"+all_total_fee);
LOGGER.debug(" --->"+refund_fee);
// out_trade_no
// all_total_fee
// refund_fee 0 all_total_fee-refund_fee=
String appid = userService.getUser().getAppid(); // --》“ ID”
String mch_id = userService.getUser().getMchId(); // , partner
String key = userService.getUser().getMchKey(); // )--》“API ”--》“API ”--“ ”( partnerkey,32 )
Map refundmap = WeiXinAtcion.me.wechatRefund(
request, mch_id, appid, key, out_trade_no, all_total_fee,
refund_fee, userService.getUser().getCert());
if (refundmap.get("return_code").equals("SUCCESS")) {
if (refundmap.get("result_code").equals("FAIL")) {
LOGGER.debug(" : " + refundmap.get("err_code_des"));
} else {
LOGGER.debug(" ");
return TTResult.ok();
}
} else {
LOGGER.debug(" : " + refundmap.get("return_ms"));
return TTResult.fail();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return TTResult.fail();
}
5.微信支払、返金パッケージを呼び出す
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.mj.mall.user.service.UserService;
import com.mj.pay.util.WXUtil;
@Controller
public class WeiXinAtcion {
public static final WeiXinAtcion me = new WeiXinAtcion();
private static final Logger LOGGER = LoggerFactory
.getLogger(WeiXinAtcion.class);
@Autowired
private UserService userService;
/**
*
*/
public static Map wechatRefund(HttpServletRequest request, String mch_id, String appid, String key, String out_trade_no, int all_total_fee, int refund_fee, String apiclient_certLocationp12) throws Exception {
SortedMap
8.WXUtilツールクラス
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WXUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(WXUtil.class);
/**
*
* @return
*/
public static String generate() {
return UUID.randomUUID().toString().trim().replaceAll("-", "");
}
/**
* xml, 。 , xml 。
*/
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if(children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = WXUtil.getChildrenText(children);
}
m.put(k, v);
}
//
in.close();
return m;
}
/**
* xml
* @param children
* @return String
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if(!children.isEmpty()) {
Iterator it = children.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("");
if(!list.isEmpty()) {
sb.append(WXUtil.getChildrenText(list));
}
sb.append(value);
sb.append("" + name + ">");
}
}
return sb.toString();
}
/**
* xml string , xml
*/
public static String getRequestXml(SortedMap parameters) {
StringBuffer sb = new StringBuffer();
sb.append("");
Set> es = parameters.entrySet();
Iterator> it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("" + "" + k + ">");
} else {
sb.append("" + v + "" + k + ">");
}
}
sb.append(" ");
return sb.toString();
}
/**
* sign , MD5 , UTF-8
*/
public static String createSign_ChooseWXPay(String characterEncoding, SortedMap parameters, String key) {
StringBuffer sb = new StringBuffer();
Set> es = parameters.entrySet();
Iterator> it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
/** , */
sb.append("key=" + key);
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
*
* @param requestUrl
* @param requestMethod
* @param outputStr
*/
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
// SSLContext
StringBuffer buffer=null;
try{
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//
if(null !=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
public static String urlEncodeUTF8(String source){
String result=source;
try {
result=java.net.URLEncoder.encode(source, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
*
*/
public static Map doRefund(HttpServletRequest request,String url,String data,String partner,String apiclient_certLocation) throws Exception {
// p12
// :“ ”--》“ ”--》“ ”--》“ ”( )--》“API ”--》“API ”--》“ ”
// apiclient_cert.p12 src ( , )
KeyStore keyStore = KeyStore.getInstance("PKCS12");
String url2 = request.getSession().getServletContext().getRealPath("/")
+ "images/cert/" + apiclient_certLocation;
LOGGER.debug("url2--->"+url2);
File file=new File(url2);
LOGGER.debug("new file");
FileInputStream instream = new FileInputStream(file);// P12
LOGGER.debug(" ");
try {
keyStore.load(instream, partner.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, partner.toCharArray()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" }, null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpPost httpost = new HttpPost(url); //
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
httpost.setEntity(new StringEntity(data, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpost);
try {
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return WXUtil.doXMLParse(jsonStr);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* , : a-z , 。
*/
public static boolean isTenpaySign(String characterEncoding, SortedMap packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
//
String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
//System.out.println(tenpaySign + " " + mysign);
return tenpaySign.equals(mysign);
}
}
9.IdUtilsツールクラス
import java.util.Random;
public class IdUtils {
/**
*
*/
public static String genImageName() {
//
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//
Random random = new Random();
int end3 = random.nextInt(999);
// 0
String str = millis + String.format("%03d", end3);
return str;
}
/**
*
* @return
*/
public static String genOrderName() {
//
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//
Random random = new Random();
long end6 = random.nextInt(999999);
// 0
String str = millis + String.format("%06d", end6);
return str;
}
}
10.MD 5 Utilツールクラス
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}