Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of source code development of Mini Program coupons

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

The knowledge points of this article "Mini Program coupon source code development method" are not quite understood by most people, so the editor summarizes the following contents for you. The content is detailed, the steps are clear, and it has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Mini Program coupon source code development method" article.

Nowadays, many offline stores have opened Mini Program and implemented coupon access to attract the flow of people, so for newcomers, how to access the coupon function is introduced below.

I. preparation before development

1: apply for Wechat official account and WeChat Mini Programs. These are two different things. You need to apply separately and have different accounts.

2: the official Wechat account needs the function of opening Wechat cards and coupons.

3: bind Mini Program in the official account of Mini Program

4: apply for Wechat open platform, and bind Wechat official account and WeChat Mini Programs to the open platform. (note: the function of binding to the development platform is only to obtain unionid, because the openid obtained by the same user under the official account and Mini Program is not the same. If both the official account and Mini Program need to collect card coupons, it is best to track users through unionid. If you only develop WeChat Mini Programs's card coupons, you can completely ignore point 4. The blogger himself did not bind to the Wechat open platform. It feels like a lot of steps, especially troublesome!)

2. Start development

1: get Wechat card coupons

Https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025272

You can obtain or create Wechat cards and coupons directly through the API provided by the official account of Wechat. Not too much information here, just mention the access_token to be obtained here. The URL is as follows: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183, and the code is as follows:

Private static String grantType = "client_credential"

Public static String appId = ante; amp / Wechat official account appid

Public static String secret = ta; amp / Wechat official account key

Public static AccessToken token = null; / / the accessToken object of the official account of Wechat. Due to the limit on the number of requests, it is saved using global static variables.

Public static AccessToken getToken () throws WeixinException, JsonParseException, JsonMappingException, IOException {

If (token = = null | | token.getExpires_in () < System.currentTimeMillis ()) {

/ / stitching parameters

String param = "? grant_type=" + grantType + "& appid=" + appId + "& secret=" + secret

/ / create a request object

HttpsClient http = new HttpsClient ()

/ / call the API to get access_token

Response res = http.get ("https://api.weixin.qq.com/cgi-bin/token" + param)

System.out.println (res.asString ())

ObjectMapper mapper = new ObjectMapper ()

Token = mapper.readValue (res.asString (), AccessToken.class)

}

Return token

}

The jar package of jackson and weixin4j is required, which is more common, so please download it yourself. The AccessToken object is also relatively simple, which is relatively simple for the four parameters errcode, errmsg, access_token and expires_in. Paste the code at the end of the article.

2: upgrade Wechat card coupons

In fact, this step can also be omitted. The purpose of upgrading Wechat card coupons is to jump directly from Wechat card coupons to the corresponding Mini Program. The blogger will be lazy and directly skip this step.

However, it is also relatively simple to upgrade the cards and coupons. You can call the API for changing Wechat cards and coupons on the official account of Wechat (URL: https://api.weixin.qq.com/card/update?access_token=TOKEN)). Add several fields. Please refer to the official document of Wechat. The link is as follows: https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=1490190158&version=1&lang=zh_CN&platform=2

3: collect card coupons

3.1: get the openId first

Mini Program end code, get code by calling wx.login, and then call https://api.weixin.qq.com/sns/jscode2session API to obtain openid. Bloggers see many examples of calling this interface directly from mini programs, but I found that it doesn't work in fact, because this domain name cannot be added to Mini Program's request legitimate domain name. The instructions given by Wechat are not to call this API at the front end, but to go through the background.

Wx.login ({

Success: function (res) {

Var service_url = 'https://???/???/weixin/api/login?code=' + res.code;// needs to add the server domain name to the legitimate request domain name of Mini Program, and it must start with https

Wx.request ({

Url: l

Data: {}

Method: 'GET'

Success: function (res) {

Console.log (res)

If (res.data! = null & & res.data! = undefined & & res.data! =') {

Wx.setStorageSync ("openid", res.data.openid); / / save the acquired openid to the cache

}

}

});

}

});

Back-end java code

/ * *

* log in to Mini Program backend, send a request to obtain access_token to Wechat platform, and return openId

* @ param code

* @ return user credentials

* @ throws WeixinException

* @ throws IOException

* @ throws JsonMappingException

* @ throws JsonParseException

, /

@ RequestMapping ("login")

@ ResponseBody

Public Map login (String code, HttpServletRequest request) throws WeixinException, JsonParseException, JsonMappingException, IOException {

If (code = = null | | code.equals ("")) {

Throw new WeixinException ("invalid null, code is null.")

}

Map ret = new HashMap ()

/ / stitching parameters

String param = "? grant_type=" + grant_type + "& appid=" + appid + "& secret=" + secret + "& js_code=" + code

System.out.println ("https://api.weixin.qq.com/sns/jscode2session" + param)

/ / create a request object

HttpsClient http = new HttpsClient ()

/ / call the API to get access_token

Response res = http.get ("https://api.weixin.qq.com/sns/jscode2session" + param)

/ / determine whether the verification is successful according to the result of the request

JSONObject jsonObj = res.asJSONObject ()

If (jsonObj! = null) {

Object errcode = jsonObj.get ("errcode")

If (errcode! = null) {

/ / return exception information

Throw new WeixinException (getCause (Integer.parseInt (errcode.toString ()

}

ObjectMapper mapper = new ObjectMapper ()

OAuthJsToken oauthJsToken = mapper.readValue (jsonObj.toJSONString (), OAuthJsToken.class)

Ret.put ("openid", oauthJsToken.getOpenid ())

}

Return ret

}

The fields of OAuthJsToken object are: openid, expires_in, session_key (session key), and paste the code at the end of the article

3.2: generate the signature of the card coupon, and call the wx.addCard method to collect the card coupon

Post the java back-end code here

Public static ApiTicket ticket = null;// uses global static variables to store ApiTicket objects. Of course, it would be better to use a cache framework to save them. Here is just a simple example.

/ * *

* @ Description: get parameters such as getting card coupons and signatures.

* @ param cardId: the cardId of the card coupon to be collected

* @ return

* @ throws WeixinException

* @ throws JsonParseException

* @ throws JsonMappingException

* @ throws IOException

, /

@ RequestMapping ("getCardSign")

@ ResponseBody

Public Map getCardSign (String cardId) throws WeixinException, JsonParseException, JsonMappingException, IOException {

Map ret = new HashMap ()

/ / first, you need to get the api_ticket. Because the API requesting api_ticket has a limit on the number of times it can be accessed, it is best to save the obtained api_ticket in the cache. This method is relatively simple and static variables are directly used.

If (ticket = = null | | ticket.getExpires_in () < System.currentTimeMillis ()) {

/ / create a request object

HttpsClient http = new HttpsClient ()

ObjectMapper mapper = new ObjectMapper ()

AccessToken token = OpenApi.getToken (); / / the token obtained here is the global static variable token of the official account of Wechat saved by the top code.

/ / obtain the api_ticket interface through access_token call

Response res = http.get ("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token.getAccess_token () +" & type=wx_card ")

System.out.println (res.asString ())

Ticket = mapper.readValue (res.asString (), ApiTicket.class)

}

Ret = sign (ticket.getTicket (), cardId); / / generate the signature needed to collect the card coupon and return the relevant parameters

For (Map.Entry entry: ret.entrySet ()) {

System.out.println (entry.getKey () + "," + entry.getValue ())

}

Return ret

}

/ * *

* @ Description: generate the signature required for the card coupon and return the parameters

* @ param api_ticket:

* @ param cardId: the cardId of the card coupon to be collected

* @ return

, /

Public static Map sign (String api_ticket, String cardId) {

Map ret = new HashMap ()

String nonce_str = create_nonce_str ()

String timestamp = create_timestamp ()

String signature = ""

String param [] = new String [4]

Param [0] = nonce_str

Param [1] = timestamp

Param [2] = api_ticket

Param [3] = cardId

Arrays.sort (param); / / A lexicographic sort of strings for the value of the parameter

StringBuilder sb = new StringBuilder ()

For (String b: param) {

Sb.append (b)

}

System.out.println (sb)

/ / A pair of concatenated strings are encrypted with sha1 to get signature

Try {

MessageDigest crypt = MessageDigest.getInstance ("SHA-1")

Crypt.reset ()

Crypt.update (sb.toString () .getBytes ("UTF-8")

Signature = byteToHex (crypt.digest ())

} catch (NoSuchAlgorithmException e) {

E.printStackTrace ()

} catch (UnsupportedEncodingException e) {

E.printStackTrace ()

}

/ / return the parameters required to collect the card coupon, in which nonceStr and timestamp must be consistent with those in the signature

Ret.put ("card_id", cardId)

Ret.put ("api_ticket", api_ticket)

Ret.put ("nonceStr", nonce_str)

Ret.put ("timestamp", timestamp)

Ret.put ("signature", signature)

Return ret

}

The properties of ApiTicket object are: errcode, errmsg, ticket, expires_in

The above is about the content of this article on "Mini Program coupon source code development methods", I believe we all have a certain understanding, I hope the content shared by the editor will be helpful to you, if you want to know more related knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report