springboot 통합 알 리 페 이 결제 의 예제 코드
10621 단어 springboot알 리 페 이지불 하 다.
1 등록 샌 드 박스
샌 드 박스 는 아 날로 그 환경 로그 인 입 니 다.바 이 두 개미 금 복 오픈 플랫폼 입 니 다.알 리 페 이 스 스 캔 코드 는 다음 과 같 습 니 다.
그리고 샌 드 박스 는 등록 이 필요 합 니 다.아주 간단 합 니 다.등록 한 후에 다음 페이지 에 들 어가 샌 드 박스 도 구 를 선택 한 다음 키 를 만 드 는 도 구 를 다운로드 하 십시오.그리고 압축 을 풀 고 안에 있 는 readme 에 따라 공유 키 를 생 성 합 니 다.
샌 드 박스 를 선택 하여 공개 키 를 올 리 면 됩 니 다.샌 드 박스 는 여기까지 입 니 다.샌 드 박스 버 전의 안 드 로 이 드 앱 도 다운로드 할 수 있 습 니 다.
자바 프로그램
1 새 springboot 프로젝트
우리 가 만 든 것 은 웹 프로젝트 이기 때문에 알 리 페 이의 demo 를 보 여 주 는 것 만으로 도 웹 을 선택 하면 충분 합 니 다.
2 알 리 페 이-sdk-자바 와 fastjson 추가
fastjson 의 역할 은 그 중의 JSON.toString 방법 을 사용 한 것 이다.
알 리 페 이-sdk-자바 의 역할 은 물론 알 리 페 이의 sdk 입 니 다.빠 질 수 없습니다.
<dependency>
<groupId>com.alipay.api</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>20170615110434</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
3 Config알 리 페 이 를 새로 만 든 config 파일 은 다음 과 같 습 니 다.
알 리 페 이 결제 완료 후 리 셋 함수 가 업 체 페이지 로 돌아 오기 때 문 입 니 다.
이 페이지 가 끝나 면 리 셋 이 있 습 니 다.리 셋 주 소 는 반드시 네트워크 가 직접 방문 할 수 있어 야 하기 때 문 입 니 다.이것 은 바로 아래 에 netapp 맵 을 사용 한 이유 입 니 다.neturl 은 매 핑 된 네트워크 주소 입 니 다.
package com.example.pay.config.pay;
import org.springframework.context.annotation.Configuration;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author ligen
* @title: AliPayConfig
* @projectName demo
* @description:
* @date 2019/6/1014:20
*/
@Configuration
public class AliPayConfig {
//↓↓↓↓↓↓↓↓↓↓ ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// netapp ,,,
private static String neturl = "http://g5kike.natappfree.cc";
// ID, APPID, APPID
public static String app_id = "2016092800619078";
// , PKCS8 RSA2
public static String merchant_private_key =" ";
// , APPID 。 ,
public static String alipay_public_key = " ";
// http:// , ?id=123 , URL
public static String notify_url = neturl+"/alipay/notify_url";
// http:// , ?id=123 , URL
public static String return_url = neturl+"/alipay/return_url";
//
public static String sign_type = "RSA2";
//
public static String charset = "utf-8";
//
public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
//
public static String log_path = "C:\\";
//↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
/**
* , ( , )
* @param sWord
*/
public static 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();
}
}
}
}
}
4 Service알 리 페 이의 결제 인 터 페 이 스 를 호출 하 는 것 은 알 리 페 이 SDK 의 인 터 페 이 스 를 통 해 알 리 페 이의 서버 에 데 이 터 를 보 내 고 비밀 번 호 를 입력 하여 결 제 를 확인 하 는 인터페이스 로 돌아 가 는 것 이다.
그래서 두 가지 만 해 야 돼 요.
1 조립 데이터
데 이 터 는 최소 5 가지 가 있 습 니 다.map 의 key 와 value 는 모두 문자열 입 니 다.
2 클 라 이언 트 만 들 기
Client 인 스 턴 스 를 만 듭 니 다.그 값 은 Config 의 값 입 니 다.
3 송신 자료
이 안 에는 먼저 데 이 터 를 request 로 바 꾸 고 마지막 으로 request 를 Client 를 통 해 보 냅 니 다.fastjson 의 toString 방법 을 사 용 했 습 니 다.바로 앞에서 fastjson 의존 도 를 가 져 온 이유 입 니 다.
package com.example.pay.config.pay;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.pay.domain.AlipayVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author ligen
* @title: AliPayService
* @projectName demo
* @description:
* @date 2019/6/119:11
*/
@Service
public class AliPayService {
Logger logger = LoggerFactory.getLogger("AliPayService.class");
@Autowired
AlipayVo staticVo;
//
public String aliPay() throws AlipayApiException {
//
Map<String, String> data = new HashMap<>();
data.put("subject", staticVo.getSubject()); //
data.put("out_trade_no", new SimpleDateFormat().format(new Date())); // ,64 、 、 、 ; //
data.put("timeout_express", staticVo.getTimout_express()); //
data.put("total_amount", staticVo.getTotle_amout()); // , , , [0.01,100000000]
data.put("product_code", "FAST_INSTANT_TRADE_PAY"); // , , QUICK_MSECURITY_PAY
//
DefaultAlipayClient alipayRsa2Client = new DefaultAlipayClient(
AliPayConfig.gatewayUrl,
AliPayConfig.app_id,
AliPayConfig.merchant_private_key,
"json",
AliPayConfig.charset,
AliPayConfig.alipay_public_key,
AliPayConfig.sign_type);
// AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();// APP
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); //
// AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest(); // h5
request.setNotifyUrl(AliPayConfig.notify_url);
request.setReturnUrl(AliPayConfig.return_url);
request.setBizContent(JSON.toJSONString(data));
logger.info(JSON.toJSONString(data));
String response = alipayRsa2Client.pageExecute(request).getBody();
logger.info(response);
return response;
}
}
5 controller 층 은 간단 합 니 다.코드 는 다음 과 같 습 니 다.
package com.example.pay.controller;
import com.alipay.api.AlipayApiException;
import com.example.pay.config.pay.AliPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
@author ligen
@title: PayController
@projectName demo
@description:
@date 2019/6/1013:25
*/
@Api(tags = “ ”)
@RestController
public class PayController {
Logger logger = LoggerFactory.getLogger("PayController.class");
@Autowired
AliPayService aliPayService;
@ApiOperation(" ")
@RequestMapping(value = "alipay/toPay/{amount}", method = RequestMethod.GET)
public String alipay(@PathVariable(value = "amount") Integer amount) throws AlipayApiException {
return aliPayService.aliPay(amount);
}
@ApiOperation(" ")
@GetMapping("alipay/notify_url")
public String notifyAlipay() {
logger.info("----notify-----");
return " a li pay notify ";
}
@ApiOperation(" ")
@GetMapping("alipay/return_url")
public String returnAlipay() {
logger.info("----return-----");
return " a li pay return ";
}
}
운행브 라 우 저 접근(포트 번 호 를 1234 로 설 정 했 습 니 다)경로 맨 뒤에 200 은 금액 매개 변수 입 니 다.
다음 페이지 로 이동 합 니 다.
이 때 샌 드 박스 알 리 페 이 앱 으로 결제 할 수 있 습 니 다.여기 계 정 으로 로그 인 합 니 다.결제 사용자 가 아 닌 로그 인 을 기억 하 세 요.그럼 계산 은 어디서 볼 까요?
개미 금 복 열기->개발 자 센터->샌 드 박스 아래 그림
두 번 째 계 정 에 로그 인 한 후 아래 그림 과 같이 비밀 번 호 는 기본적으로 111111 입 니 다.
return url 을 설정 하면 이 페이지 가 끝 난 후에 return url 에 대응 하 는 페이지 로 자동 으로 이동 합 니 다.다음 과 같이 return url 에서 문자열 만 되 돌려 주 었 습 니 다.
코드 git 주소
https://github.com/ligengithub/pay.git
이로써 spring boot 통합 알 리 페 이 결제 에 관 한 예제 코드 에 관 한 글 은 여기까지 소개 되 었 습 니 다.더 많은 spring boot 통합 알 리 페 이 결제 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin Springboot -- 파트 14 사용 사례 REST로 전환하여 POST로 JSON으로 전환前回 前回 前回 記事 の は は で で で で で で を 使っ 使っ 使っ て て て て て リクエスト を を 受け取り 、 reqeustbody で 、 その リクエスト の ボディ ボディ を を 受け取り 、 関数 内部 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.