최근에 WeChat 공개 계정 지불은 처음으로 수행 되었기 때문에 며칠 동안 탐구되었으며, 구현 수준에 도달했습니다
WeChat 공개 계정의 전반적인 지불은 실제로 매우 간단하며 대략 세 단계로 나뉩니다. 첫 번째 단계는 사용자 승인에 의해 얻어야합니다. 다음은 각 단계의 개발 과정을 소개합니다.
우선, WeChat Public 계정 결제가 웹 버전 결제임을 명확히해야하므로 앱이 직접 weChat 결제보다 직접 검색된 것보다 한 단계 더 weChat 승인이 필요합니다. 즉, 사용자의 OpenID를 얻어야합니다. WeChat Public Account에서 사용하는 트랜잭션 유형은 JSAPI이므로 Unified Order 인터페이스의 문서는
따라서 우리는 OpenID를 얻어야하며 동시에 필요한 논리를 처리 할 수 있습니다. 사용자 승인을 얻는 두 가지 방법이 있습니다. 1.Scope = snsapi_base;
범위는 snsapi_base입니다
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&rdirect_uri=http%2fchong.qq.com%2fphpph%2findex.php%3d%26c%26mout%26mout%3d aytitle% 3D1%26VB2CTAG%3D4_2030_5_1194_60 & response_type = code & scope = snsapi_base & state = 123#wechat_redirect
스코프는 snsapi_userinfo입니다
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3a%3a% #wechat_redirect
WeChat의 공식 문서에는 각 매개 변수에 대한 자세한 설명이 있으며 주요 매개 변수를 신중하게 설명하겠습니다. 우선, wechat 공개 계정의 appid가 readirect_uri 매개 변수가 가장 중요하다고 말할 수 없습니다. 이 링크에 필요한 매개 변수를 스티치 할 수 있습니다. 상태 매개 변수는 확장 된 필드로 이해 될 수 있습니다. 다음은 OpenID의 코드 클립입니다.
// OpenID httpclientutil util = httpclientutil.getInstance () <string = string, String> (); , wxpayconfig.appsecret); "코드", "grant_type"; /sns/oauth2/access_token ", null, map); logger.info ("returnstr : [ " + returnstr +"] "); AccessStoken at = json.parseobject (returnstr, accessStoken.c lass);accesstoken.java
공개 AccessStoken {private String eppribe expribe; return expires_in;} public void setexpires_in (string expires_in) {this.expires_in = expires_in; public void setrefresh_token (string refresh_token) {retresh_token = refresh_token;}} OpenID;} public void setopenid (String OpenID) {this.openid = openID;} public string e () {return scope;} public void setScope (String scope) {this.scope = scope;} public string getUnionid () {return unionid;} Public Void Setunionid (String Unionid) {this.unionid = unionid; String tostring () {Return "AccessStoken [Access_token =" + Access_token + ", Expires_in = " + Expires_in +", Refresh_token = " + Refresh_token +", OpenID = " + OpenID +", scope = " + scope +", unionID = " + unionId +"] "]"] ""둘째, OpenID를 얻은 후 다음 통합 명령 배치를 수행 할 수 있습니다. WeChat의 단일 인터페이스 문서가 더 자세하고 특정 매개 변수 의미를 소개하지 않습니다. 가장 직관적 인 코드는 아래에 게시되어 있으며, 특히 올바른 서명에주의를 기울여야한다는 것을 상기시켜줍니다. 서명에 사용 된 키는 AppSecret이 아니라 신청할 때 정의한 판매자 키입니다.
// Uniform the order wxpaysenddata data = new wxpaysenddata (); data.setAppid (wxpayconfig.appid); data.Setattach ("WeChat Pay"); Data.SetBody ("WeChat public account payment"); tmch_id (wxpayconfig. Mchid) ; data.setnonce_str (noncestr); data.setnotify_url (wxpayconfig.notify_url); data.setout_trade_no (tradeno); ) (Fee*100)); // Unit: Data.Settrade_type ("" Jsapi "); data.setspbill_create_ip ( ip); data.setOpenid (at.getOpenid ()); String Returnxml = UnifiedRederservice.unifiedorder (data, wxpayconfigig .Key); wxpayreturndata redata = new wxpayreturndata (); xstream xs1 = new xstream ( new domdriver ()); xs1. 별칭 ( "XML", wxpayreturndata.class);UnifiedorderService.java
Public Class UnifiedOrderService {Private Final Static Logger = LoggerFactory.getLogger (UnifiedOrnderService.class); Public Static String FIEDORDER (WXPAYSENDATA DATA, String Key) {// Uniform order to pay String Returnxml = Null; try {// generate sidn signature sortedMap < Object, object> Parameters = New Treemap <object, object> (); Parameters.put ("appid", data.getAppid ()); h ()); Parameters.put ("Body", Data.getBody ()) ; Parameters.put ("mch_id", data.getmch_id ()); parameters.put ("nonce_str", data.getnonOnonce_Str ()); fy_url ", data.getNotify_url ()); Parameters.put ("OUT_TRADE_NO", Data .getout_trade_no ()); Parameters.put ("Total_fee", data.gettotal_fee eters.put ("trade_type", data.gettrade_type () );; "SPBILL_CREATE_IP", Data.getspbill_Create_ip ()); Parameters.put ("Openid ", Data.getOpenid ()); Parameters.put ("Device_info", D ata.getDevice_info ()); logger.info ("Sign:"+WXSIGN.CREATESIGN (Parameters, Key)); F-8 ", New XMLFRIENDLYNAMECODER ("- _ "," _ ")); xs.alias (" xml ", wxpaysenddata.class); string xml = xs.toxml (data); logger.info (" Unified order xml is:/n " + xml) ; HttpClientUtil Util = httpclientutil.getInstance (); Returnxml = Util.dopostForsstring ("https://api.mch.qq.com/pay/unifiedRder", NU ll, xml); logger.info ("Return Result: " + returnxml);} catch (예외 e) {e.printstacktrace ();} return returnxml;}}}}}}}}wxsign
Public class wxsign {Private Static String CharacterErencoding = "UTF-8"; @SuppressWarnings ("Rawtypes") Public Static String (SorteDMap <obj Ect, Object> Parameters, String Key) {StringBuffer Sb = New StringBuffer (); Set ES = 매개 변수에 참여하는 모든 매개 변수는 계정 (프로모터) 반복에 따라 정렬됩니다. 다음 (); String k = (string) getKey (); {sb.append (k + "=" + v + "&");}} sb.append ( "key =" + key); ); reption 부호;} public static string getNoStr () {random random = retrand Ode (random.nextInt (10000)), "UTF-8"); {return string.valueof (System.CurrentTtimemillis () / 1000);}}마지막으로 언급해야 할 것은 WeChat 결제 비동기 알림 콜백 주소를 수신하기위한 Notify_url 콜백 주소입니다.
우리는 마지막 단계 작업을 수행 할 수 있도록 사전 지불 트랜잭션의 준비를 얻었습니다. H5를 사용하여 결제 API를 조정하십시오.
// h5 결제 attr.AdDattRibute ( "appid", redata.getAppid ()); ); att "appid", redata.getAppid ()); ); SignMap.put ( "signType", "md5"); ", wxsign.createsign (signmap, wxpayconfig.key));
필요한 매개 변수를 페이지에 전달한 후 WeChat을 사용하여 결제를 설정하는 방법을 제공하십시오.
<cript> 함수 geturlparam (name) {// 대상 매개 변수를 포함하는 정규 표현 객체를 구성 var var reg = new regexp ( "(^| &)" + name + "= (^&]*) (& | $)). "); // 대상 매개 변수 var r = wink null; 'signtype'); var paysign = geturlparam ( 'paysign'); timestamp, // "1395712654", // timelia, 1970 년 이후 두 번째 초의 "비정부": noncest, // "e61463f8efa94090b1f366ccccccccccccccccccccccccccccccccccccccccccccfbbbb44", // random string "package"ge, // "pleray_id = u802345jgsdg. ": SignType, //"md5 ", // weChat 서명 메소드 :"PaySign ": PaySign, //"70EA570631E4BB79628FBCA905343FFADD89 ""// wechat 서명}, function (res) {// 위의 메소드를 사용하여 전면 종료 뒤로, WeChat 팀은 엄숙하게 상기시켜줍니다. res.err_msg는 사용자가 성공적으로 지불 한 후에도 OK로 돌아갑니다. get_brand_wcpay_request : cancel ") {alert ("트랜잭션 취소 ");} if (res.err_msg =="get_wcpay_request : fail ") lert ("지불 실패 "); == "underfined") {if (document.addeventlistener) {document.addeventListener ( 'wei xinjsbridgeready', onbridgeready, false); att결과를 반환하는 자신의 반환 페이지를 사용자 정의 할 수 있습니다.
요약 : 처음 으로이 기사를 작성하는 것은 내 작업 결과를 기록하는 것입니다 진전.
위는 Java의 Wechat 공개 지불의 모든 내용입니다.