WeChat official account payment H5 call payment details, h5 details

Source: Internet
Author: User
Tags oauth openid

Public Account Payment H5 call payment details, h5 details

Recently, I had to pay for the project and read the public account to pay for it. Although it is not difficult, I still need to pay attention to the details. I wrote a demo for a long time, and the complete test of the payment process, the following shares the experience of public account payment.


1. Configure public account payment

We need to configure the public account payment address and test the White List.

For example, the address of the JS page for payment is http://www.xxx.com/shop/pay/

Configure www.xxx.com/shop/pay/


2. Development Process

Borrow a public account to pay api (address http://pay.weixin.qq.com/wiki/doc/api/index.php? Chapter = 7_4). We need to mark it in red. As follows:

 

3. place an order with the server

Call the unified order interface, so that you can get the prepay_id of the payment (http://pay.weixin.qq.com/wiki/doc/api/index.php? Chapter = 9_1 ).

Before calling this interface, there are several fields that are required for H5 payment: openid

3.1 obtain openid

Can be authorized through web pages (http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html)

Send the following link in

Https://open.weixin.qq.com/connect/oauth2/authorize? Appid = wx520c15f415810387 & redirect_uri = url of the order to be redirected & response_type = code & scope = snsapi_base & state = 123 # wechat_redirect


3.2 place an order and get prepay_id

The Code is as follows. In fact, an xml file is sent through post to obtain the prepay_id sent by the server.

Import java. io. byteArrayInputStream; import java. io. IOException; import java. io. inputStream; import java. io. unsupportedEncodingException; import java. util. date; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. map. entry; import java. util. random; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. commons. codec. Digest. digestUtils; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; import org. xmlpull. v1.XmlPullParser; import org. xmlpull. v1.XmlPullParserException; import org. xmlpull. v1.XmlPullParserFactory; import com. fasterxml. jackson. databind. jsonNode; import com. gson. oauth. oauth; import com. gson. oauth. pay; import com. gson. util. httpKit; import com. sy. u Til. datetimeUtil; import com. sy. util. jsonUtil; @ Controller @ RequestMapping ("/pay") public class WXPayController {@ RequestMapping (value = "wxprepay. do ") public void jspay (HttpServletRequest request, HttpServletResponse response, String callback) throws Exception {// obtain openidString openId = SessionUtil. getAtt (request, "openId"); if (openId = null) {openId = getUserOpenId (request);} String appid = "wx16691 Fcb0523c1a4 "; String paternerKey =" regular "; String out_trade_no = getTradeNo (); Map <String, String> paraMap = new HashMap <String, String> (); paraMap. put ("appid", appid); paraMap. put ("attach", "test"); paraMap. put ("body", "Test purchase payment"); paraMap. put ("mch_id", "10283271"); paraMap. put ("nonce_str", create_nonce_str (); paraMap. put ("openid", openId); paraMap. put ("out_trade_no", out_trade_no ); ParaMap. put ("spbill_create_ip", getAddrIp (request); paraMap. put ("total_fee", "1"); paraMap. put ("trade_type", "JSAPI"); paraMap. put ("yy_url", "http://www.xxx.co/bank/page/wxnotify"); String sign = getSign (paraMap, paternerKey); paraMap. put ("sign", sign); // unified order https://api.mch.weixin.qq.com/pay/unifiedorderString url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; String xml = ArrayToXml (paraM Ap); String xmlStr = HttpKit. post (url, xml); // prepaid item idString prepay_id = ""; if (xmlStr. indexOf ("SUCCESS ")! =-1) {Map <String, String> map = doXMLParse (xmlStr); prepay_id = (String) map. get ("prepay_id");} Map <String, String> payMap = new HashMap <String, String> (); payMap. put ("appId", appid); payMap. put ("timeStamp", create_timestamp (); payMap. put ("nonceStr", create_nonce_str (); payMap. put ("signType", "MD5"); payMap. put ("package", "prepay_id =" + prepay_id); String paySign = getSign (payMap, paternerKey); payMap. pu T ("pg", prepay_id); payMap. put ("paySign", paySign); WebUtil. response (response, WebUtil. packJsonp (callback, JsonUtil. warpJsonNodeResponse (JsonUtil. objectToJsonNode (payMap )). toString ();}/*** map to xml ** @ param arr * @ return */public String ArrayToXml (Map <String, String> arr) {String xml = "<xml>"; Iterator <Entry <String, String> iter = arr. entrySet (). iterator (); while (iter. hasNext () {Entry <String, String> entry = iter. next (); String key = entry. getKey (); String val = entry. getValue (); xml + = "<" + key + ">" + val + "</" + key + "> ";} xml + = "</xml>"; return xml;} // obtain openIdprivate String getUserOpenId (HttpServletRequest request) throws Exception {String code = request. getParameter ("code"); if (code = null) {String openId = request. getParameter ("openId"); return openId;} Oauth o = new Oauth (); Stri Ng token = o. getToken (code); JsonNode node = JsonUtil. stringToJsonNode (token); String openId = node. get ("openid "). asText (); return openId;} private String create_nonce_str () {String chars = "Hangzhou"; String res = ""; for (int I = 0; I <16; I ++) {Random rd = new Random (); res + = chars. charAt (rd. nextInt (chars. length ()-1);} return res;} private Strin G getAddrIp (HttpServletRequest request) {return request. getRemoteAddr ();} private String create_timestamp () {return Long. toString (System. currentTimeMillis ()/1000);} private String getTradeNo () {String timestamp = DatetimeUtil. formatDate (new Date (), DatetimeUtil. DATETIME_PATTERN); return "HZNO" + timestamp;} private String getSign (Map <String, String> params, String paternerKey) throws UnsupportedEncodi NgException {String string1 = Pay. createSign (params, false); String stringSignTemp = string1 + "& key =" + paternerKey; String signValue = DigestUtils. md5Hex (stringSignTemp ). toUpperCase (); return signValue;} private Map <String, String> doXMLParse (String xml) throws XmlPullParserException, IOException {InputStream inputStream = new ByteArrayInputStream (xml. getBytes (); Map <String, String> map = null; XmlPul LParser pullParser = XmlPullParserFactory. newInstance (). newPullParser (); pullParser. setInput (inputStream, "UTF-8"); // set the xml data int eventType = pullParser for xml to be parsed. getEventType (); while (eventType! = XmlPullParser. END_DOCUMENT) {switch (eventType) {case XmlPullParser. START_DOCUMENT: map = new HashMap <String, String> (); break; case XmlPullParser. START_TAG: String key = pullParser. getName (); if (key. equals ("xml") break; String value = pullParser. nextText (); map. put (key, value); break; case XmlPullParser. END_TAG: break;} eventType = pullParser. next () ;}return map ;}}

Iv. H5 payment

H5 payment is actually very simple, just need to call embedded browser js method on the line (http://pay.weixin.qq.com/wiki/doc/api/index.php? Chapter = 7_7)

<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" spring "uri =" http://www.springframework.org/tags "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 

The effect is as follows:




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.