Uniform order interface Implementation Method for app payment, app order
In groovy, You Can Use https to call the unified ordering interface of app payment, which is basically the same as java. to parse xml, You need to import the jar packages of dom4j and jaxen.
Import groovy. SQL. sqlimport org. dom4j. specified entimport org. dom4j. documentExceptionimport org. dom4j. documentHelperimport org. dom4j. elementimport java. security. messageDigest/*** dom4j parses xml * tool class FOR post request using HttpClient */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
() // Application APPID params approved by the open platform. put ("appid", "") // The Merchant ID of the payment allocation, params. put ("mch_id", "") // random string params. put ("nonce_str", "") // item description params. put ("body", "test") // The Merchant's Order Number (params. put ("out_trade_no", "") // total params. put ("total_fee", "1") // Terminal IP address params. put ("spbill_create_ip", "") // notification address params. put ("policy_url", ") // transaction type params. put ("trade_type", "APP") // signature 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} // payment request 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) // set the Request Method (GET/POST) conn. setRequestMethod (requestMethod) conn. setRequestProperty (" Content-type "," application/x-www-form-urlencoded ") // when outputStr is not null, write data to the output stream if (null! = OutputStr) {OutputStream outputStream = conn. getOutputStream () // note the encoding format outputStream. write (outputStr. getBytes ("UTF-8") outputStream. close ()} // read the returned content from the input stream InputStream inputStream = conn. getInputStream () InputStreamReader inputStreamReader = new InputStreamReader (inputStream, "UTF-8") BufferedReader bufferedReader = new BufferedReader (inputStreamReader) String str StringBuffer buffer = new Str IngBuffer () while (str = bufferedReader. readLine ())! = Null) {buffer. append (str)} // release the resource bufferedReader. close () inputStreamReader. close () inputStream. close () conn. disconnect () return buffer. toString ()} catch (ConnectException ce) {println "connection Timeout:" + ce} catch (Exception e) {println ("https request Exception" + e )} return null}/*** map to an xml format String */static String map2XmlString (Map
Map) {String xmlResult StringBuffer sb = new StringBuffer () sb. append ("
") For (String key: map. keySet () {String value ="
"Sb. append (" <"+ key +"> "+ value +"
")} Sb. append ("
") XmlResult = sb. toString () return xmlResult}/*** converts an xml string to map */static Map
ReadXmlString2Map (String xml) {Map
Map = new HashMap
() Document doc try {doc = incluenthelper. parseText (xml) // convert the string to XML Element rootElt = doc. getRootElement () // obtain the root node List
List = rootElt. elements () // obtain all nodes under the root node for (Element element: list) {// traverse the node map. put (element. getName (), element. getText () // The node name is the key of the map, and text is the value of the map} catch (DocumentException e) {e. printStackTrace ()} catch (Exception e) {e. printStackTrace ()} return map} private String createSign (params) {StringBuffer sb = new StringBuffer () Set es = params. entrySet () // lexicographically 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 + "&")} // splice the key in step 2. Set the path of the key: merchant platform (pay.weixin.qq.com) --> account settings --> API security --> key settings sb. append ("key =" + "112233445566778899 mukitechheqiao") String sign = MD5Util. MD5Encode (sb. toString (), "UTF-8 "). toUpperCase () // MD5 encrypted 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. getI Nstance ("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) // Add data to obtain the 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 .exe cute (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 .exe cuteUpdate (statement, params) return affected_rows} // query a def selectOne (statement, params) {def result SQL. eachRow (statement, params) {row-> result = row. toRowResult ()} return result} // query def getByPrimaryKey (table, Key, id) {def statement = "select * from $ table where $ key =? ". ToString () def result = selectOne (statement, [id]) return result} // query multiple data records def selectList (statement, params) {def resultSet = [] SQL. eachRow (statement, params) {row-> def result = row. toRowResult () resultSet. add (result)} return resultSet} // count 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} // a dynamic multi-condition query 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 }}}