javascript
Springboot 服务端为App集成支付宝支付
別整什么花里胡哨的,先去吧官方文檔看一遍。
首先把準備的東西準備好,這里加上一個大佬寫的的連接:https://blog.csdn.net/vbirdbest/article/details/80635194?前期準備工作所需要的都在這里了。
登錄上螞蟻金服,點開發中心->網頁&移動應用去看一下你申請的應用狀態是不是已上線。
?點擊查看詳情:
在左邊導航欄找到應用信息,點開大概就可以看到你app的信息了。
?
你需要配置:應用網關,授權回調地址。
https://docs.open.alipay.com/291/106097/?這是RSA密鑰工具。具體使用可以去里面看一下。
上代碼:
1、pom依賴:
<!--支付寶支付依賴--><dependency><groupId>net.guerlab</groupId><artifactId>sdk-alipay-starter</artifactId><version>1.0.3</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.38</version></dependency>2、支付寶配置文件
import java.io.FileWriter; import java.io.IOException;/*** 支付寶支付基礎配置文件*/ public class AlipayConfig {// 應用ID,您的APPID,收款賬號既是您的APPID對應支付寶賬號public String app_id = "";// 商戶私鑰,您的PKCS8格式RSA2私鑰public String merchant_private_key = "";// 支付寶公鑰,查看地址:https://openhome.alipay.com/platform/keyManage.htm 對應APPID下的支付寶公鑰。public String alipay_public_key = "";// 服務器異步通知頁面路徑 需http://格式的完整路徑,不能加?id=123這類自定義參數,必須外網可以正常訪問public String notify_url = "";// 頁面跳轉同步通知頁面路徑 需http://格式的完整路徑,不能加?id=123這類自定義參數,必須外網可以正常訪問// public String return_url = "";// 簽名方式public String signType = "RSA2";// 字符編碼格式public String charset = "utf-8";// 支付寶請求地址public String gatewayUrl = "https://openapi.alipay.com/gateway.do";// 支付寶網關public String log_path = "C:\\";//支付寶僅支持JSON格式public String format="JSON";public String getApp_id() {return app_id;}public void setApp_id(String app_id) {this.app_id = app_id;}public String getMerchant_private_key() {return merchant_private_key;}public void setMerchant_private_key(String merchant_private_key) {this.merchant_private_key = merchant_private_key;}public String getAlipay_public_key() {return alipay_public_key;}public void setAlipay_public_key(String alipay_public_key) {this.alipay_public_key = alipay_public_key;}public String getNotify_url() {return notify_url;}public void setNotify_url(String notify_url) {this.notify_url = notify_url;}// public String getReturn_url() { // return return_url; // } // // public void setReturn_url(String return_url) { // this.return_url = return_url; // }public String getSignType() {return signType;}public void setSignType(String signType) {this.signType = signType;}public String getCharset() {return charset;}public void setCharset(String charset) {this.charset = charset;}public String getGatewayUrl() {return gatewayUrl;}public void setGatewayUrl(String gatewayUrl) {this.gatewayUrl = gatewayUrl;}public String getLog_path() {return log_path;}public void setLog_path(String log_path) {this.log_path = log_path;}public String getFormat() {return format;}public void setFormat(String format) {this.format = format;}public void logResult(String sWord) {FileWriter writer = null;try {writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt");writer.write(sWord);} catch (Exception e) {e.printStackTrace();} finally {if (writer != null) {try {writer.close();} catch (IOException e) {e.printStackTrace();}}}}}3、service層:
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map;public interface ALiservice {/*** 統一下單* @param total_fee 總價* @param oid 訂單ID* @return* @throws Exception*/Map pay(String total_fee, String oid) throws Exception;/*** 支付回調* @param request* @param response*/void paymentCallback(HttpServletRequest request, HttpServletResponse response); }4、serviceImpl層:
import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.AlipayTradePayModel; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.request.AlipayTradeAppPayRequest; import com.alipay.api.response.AlipayTradeAppPayResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.math.BigDecimal; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @Service public class ALiserviceImpl implements ALiservice {private static final Logger logger = LoggerFactory.getLogger("MainLogger");AlipayConfig alipayConfig = new AlipayConfig();/*** app支付接口2.0** @param total_fee 總價* @param oid 訂單ID* @return* @throws Exception*/@Overridepublic Map pay(String total_fee, String oid) throws Exception {try {System.out.println("-----------------------------支付寶預支付開始------------------------------------");// 封裝請求客戶端 實例化客戶端 這個順序不要動AlipayClient client = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getApp_id(), alipayConfig.getMerchant_private_key(),alipayConfig.getFormat(), alipayConfig.getCharset(),alipayConfig.getAlipay_public_key(),alipayConfig.getSignType());// 支付請求 實例化具體API對應的request類,類名稱和接口名稱對應,當前調用接口名稱:alipay.trade.app.payAlipayTradeAppPayRequest payRequest = new AlipayTradeAppPayRequest();// SDK已經封裝掉了公共參數,這里只需要傳入業務參數。// 以下方法為sdk的model入參方式(model和biz_content同時存在的情況下取biz_content)。AlipayTradePayModel model = new AlipayTradePayModel();model.setSubject("測試支付寶"); //訂單名稱model.setBody("測試支付寶支付"); //設置商品描述String out_trade_no = jinOrderMapper.selectOrderNum(oid); //獲取訂單號System.out.println("商戶訂單號------------" + out_trade_no);model.setOutTradeNo(out_trade_no); //設置商戶網站唯一訂單號model.setTotalAmount(total_fee); //設置總金額model.setTimeoutExpress("90m"); //設置超時關閉該訂單時間model.setProductCode("QUICK_MSECURITY_PAY");//銷售產品碼payRequest.setBizModel(model); //封裝好的額外參數放到主請求中payRequest.setNotifyUrl(alipayConfig.getNotify_url());//設置異步通知地址//支付寶請求應答AlipayTradeAppPayResponse responses = client.sdkExecute(payRequest);System.out.println("-----------------------------支付寶應答處理開始------------------------------------");System.out.println(responses.getBody()); // 就是orderString 可以直接給客戶端請求,無需再做處理Map<String, String> data = new HashMap<>();data.put("body",responses.getBody()); //支付表單return data;} catch (Exception e) {e.printStackTrace();}throw new Exception("下單失敗");}/***支付回調* @param request* @param response*/@Overridepublic void paymentCallback(HttpServletRequest request, HttpServletResponse response) {System.out.println("---------------------------支付寶進入異步通知--------------------------");String resultFail = "fail";//獲取支付寶GET過來反饋信息Map<String, String> params = new HashMap<String, String>();Map requestParams = request.getParameterMap();System.out.println("返回的map----------------" + requestParams);for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {String name = (String) iter.next();String[] values = (String[]) requestParams.get(name);String valueStr = "";for (int i = 0; i < values.length; i++) {valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";}//亂碼解決,這段代碼在出現亂碼時使用。如果mysign和sign不相等也可以使用這段代碼轉化/*try {valueStr = new String(valueStr.getBytes("ISO-8859-1"), "GBK");} catch (UnsupportedEncodingException e) {e.printStackTrace();}*/params.put(name, valueStr);}logger.info("params={}", params);boolean signVerified = false; //調用SDK驗證簽名try {signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(), alipayConfig.getSignType());} catch (AlipayApiException e) {logger.error("【支付寶異步通知】支付寶回調通知失敗 e={} params={}", e, params);responseBody(response, resultFail);return;//e.printStackTrace();}if (!signVerified) {logger.error("【支付寶異步通知】驗證簽名錯誤 params={} ", params);responseBody(response, resultFail);return;}BigDecimal trade_price = new BigDecimal(request.getParameter("total_amount"));//商戶訂單號String out_trade_no = params.get("out_trade_no");//支付寶交易號String trade_no = params.get("trade_no");//交易狀態String trade_status = params.get("trade_status");// 支付成功修改訂單狀態if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {//業務處理,主要是更新訂單狀態System.out.println("---------------------------支付成功--------------------------");}responseBody(response, resultFail);return;}private void responseBody(HttpServletResponse response, String contentBody) {try {response.setContentType("type=text/javascript;charset=UTF-8");String s = contentBody;response.getWriter().write(s);} catch (Exception e) {e.printStackTrace();}return;} }5、controller 層:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map;@RestController @RequestMapping("/alipay") public class AlipayController {@AutowiredALiserviceImpl aLiservice;/*** 支付* @param total_fee* @param oid* @return* @throws Exception*/@PostMapping("/apppay")public Map pay( @RequestParam(value = "total_fee") String total_fee,@RequestParam(value = "oid") String oid) throws Exception {return aLiservice.pay(total_fee,oid);}/*** 回調* @param request* @param response* @return*/@PostMapping("/alipayNotify")public void alipayNotify(HttpServletRequest request, HttpServletResponse response) {aLiservice.paymentCallback(request,response);}}?代碼就這些,比微信的要簡單。
你去請求支付寶返回的數據大概是這個樣子的:
?
這個不用處理直接返回給安卓就行了。
要想知道他能不能調起支付寶支付。你可以安裝一個APK:地址-》https://openclub.alipay.com/club/history/read/769
常見的錯誤就是系統繁忙ALIN10146 ?自查方案 地址-》:https://openclub.alipay.com/club/history/read/6918
----------------------------------------------------------------------------。-。-。-。-。-。-。-。-。-。-。-。-。-。-。-。。-。-。-
華麗結束
總結
以上是生活随笔為你收集整理的Springboot 服务端为App集成支付宝支付的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「领域驱动设计」DDD,六边形架构,洋葱
- 下一篇: Emacs 安装配置使用教程