在groovy中使用https调用微信app支付统一下单接口,和java基本相同,解析xml需要导入dom4j,jaxen的jar包。
import groovy.sql.Sql
import org.dom4j.Document
import org.dom4j.DocumentException
import org.dom4j.DocumentHelper
import org.dom4j.Element
import java.security.MessageDigest
/**
*dom4j解析xml
* 利用HttpClient进行post请求的工具类
*/
class wechat {
def dao = new GeneralDAO()
static main(args){
def test = new wechat()
def map = ["order_id":"1"]
def msg = test.handle(map)
println(msg)
}
def handle(map){
def order = dao.getByPrimaryKey("orders","order_id",map.order_id)
SortedMap params = new TreeMap()
//微信开放平台审核通过的应用APPID
params.put("appid","")
//微信支付分配的商户号
params.put("mch_id", "")
//随机字符串
params.put("nonce_str","")
//商品描述
params.put("body", "test")
//商户订单号
params.put("out_trade_no", "")
//总金额
params.put("total_fee", "1")
//终端IP
params.put("spbill_create_ip", "")
//通知地址
params.put("notify_url", ")
//交易类型
params.put("trade_type", "APP")
//签名
def sign = createSign(params)
params.put("sign", sign)
println(map2XmlString(params))
String xmlStr = httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",map2XmlString(params))
Map result = readXmlString2Map(xmlStr)
return result
}
// 微信支付请求
static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
try {
URL url = new URL(requestUrl)
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
conn.setDoOutput(true)
conn.setDoInput(true)
conn.setUseCaches(false)
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod)
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded")
// 当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
StringBuffer buffer = new StringBuffer()
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str)
}
// 释放资源
bufferedReader.close()
inputStreamReader.close()
inputStream.close()
conn.disconnect()
return buffer.toString()
} catch (ConnectException ce) {
println "连接超时:" + ce
} catch (Exception e) {
println("https请求异常" + e)
}
return null
}
/**
* map转xml格式字符串
*/
static String map2XmlString(Map map) {
String xmlResult
StringBuffer sb = new StringBuffer()
sb.append("")
for (String key : map.keySet()) {
String value = ""
sb.append("<" + key + ">" + value + "" + key + ">")
}
sb.append(" ")
xmlResult = sb.toString()
return xmlResult
}
/**
* 将xml字符串转换成map
*/
static Map readXmlString2Map(String xml) {
Map map = new HashMap()
Document doc
try {
doc = DocumentHelper.parseText(xml) // 将字符串转为XML
Element rootElt = doc.getRootElement() // 获取根节点
List list = rootElt.elements()// 获取根节点下所有节点
for (Element element : list) { // 遍历节点
map.put(element.getName(), element.getText()) // 节点的name为map的key,text为map的value
}
} catch (DocumentException e) {
e.printStackTrace()
} catch (Exception e) {
e.printStackTrace()
}
return map
}
private String createSign(params) {
StringBuffer sb = new StringBuffer()
Set es = params.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 (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&")
}
}
//第二步拼接key,key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
sb.append("key=" +"112233445566778899mukitechheqiao")
String sign = MD5Util.MD5Encode(sb.toString(), "utf-8")
.toUpperCase()//MD5加密
return sign
}
static 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]
}
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"]
}
class GeneralDAO {
def db = [url:'jdbc:mysql:', user:'', password:'', driver:'com.mysql.cj.jdbc.Driver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
//新增数据,获取新增记录的id
def insert(map,table){
def key = ""
def value = ""
def insert_id
def params = []
map.each{
k,v->
key = key + "$k" + ","
value = value + "?,"
params.add(v)
}
key = key[0..(key.length()-2)]
value = value[0..(value.length()-2)]
def statement = "insert into $table ( $key) values ($value)".toString()
println(statement)
println(params)
sql.execute(statement,params)
statement = "SELECT last_insert_id()"
sql.eachRow(statement){
row->
def result = row.toRowResult()
insert_id = result["last_insert_id()"]
}
return insert_id
}
//update operation,return affected rows
def update(updateMap,whereMap,table){
def up = ""
def wh = ""
def statement
def params = []
updateMap.each{
k,v->
up = up + "$k = ?,"
params.add(v)
}
whereMap.each{
k,v->
wh = wh + "$k = ? and "
params.add(v)
}
up = up[0..(up.length()-2)]
wh = wh[0..(wh.length()-6)]
statement = "update $table set $up where $wh".toString()
println(statement)
def affected_rows = sql.executeUpdate(statement,params)
return affected_rows
}
//查询一条
def selectOne(statement,params){
def result
sql.eachRow(statement,params){
row->
result = row.toRowResult()
}
return result
}
//根据主键查询
def getByPrimaryKey(table,key,id){
def statement = "select * from $table where $key = ?".toString()
def result = selectOne(statement,[id])
return result
}
//查询多条数据
def selectList(statement,params){
def resultSet = []
sql.eachRow(statement,params){
row->
def result = row.toRowResult()
resultSet.add(result)
}
return resultSet
}
//统计数量
def count(map,table){
def statement = "select count(*) as count from $table where 1=1"
def params = []
map.each{
k,v->
if(v!=null&&v!=""){
statement = statement + " and $k = ?"
params.add(v)
}
}
println(statement)
println(params)
def resultSet = selectOne(statement,params).count
return resultSet
}
//动态多条件查询
def select(map,table,sort,page,size){
def statement = "select * from $table where 1=1"
def params = []
map.each{
k,v->
if(v!=null&&v!=""){
statement = statement + " and $k = ?"
params.add(v)
}
}
if (sort!=null&&sort!=""){
statement = statement + " order by $sort "
}
if (page!=null&&page!=""){
params.add(page.toInteger()*10)
statement = statement + " limit ?,$size"
}
println(statement)
println(params)
def resultSet = sql.rows(statement,params)
return resultSet
}
}
}