package org.yeshi.utils.alipay;
|
|
import com.alibaba.fastjson.JSONObject;
|
import com.alipay.api.AlipayApiException;
|
import com.alipay.api.AlipayClient;
|
import com.alipay.api.request.AlipayOpenAppMiniTemplatemessageSendRequest;
|
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
|
import com.alipay.api.response.AlipayOpenAppMiniTemplatemessageSendResponse;
|
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
|
import org.yeshi.utils.entity.alipay.AlipayAppInfo;
|
import org.yeshi.utils.exception.AlipayXcxException;
|
|
/**
|
* 支付宝小程序帮助类
|
*/
|
public class AlipayXcxUtil {
|
|
|
/**
|
* 获取支付宝的用户ID
|
*
|
* @param app
|
* @param code
|
* @return
|
* @throws AlipayApiException
|
*/
|
public static String getUserId(AlipayAppInfo app, String code) throws AlipayApiException, AlipayXcxException {
|
AlipayClient alipayClient = AlipayUtil.getAlipayClient(app);
|
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
|
request.setGrantType("authorization_code");
|
request.setCode(code);
|
AlipaySystemOauthTokenResponse response = app.getCertInfo() != null ? alipayClient.certificateExecute(request) : alipayClient.execute(request);
|
if (!response.isSuccess()) {
|
throw new AlipayXcxException(response.getCode(), response.getSubMsg(), response.getBody());
|
}
|
return response.getUserId();
|
}
|
|
|
/**
|
* 发送模板消息
|
*
|
* @param app 应用信息
|
* @param templateId 模板ID
|
* @param page 小程序页面路径
|
* @param userId 用户ID
|
* @param formId 表单ID
|
* @param params
|
* @return
|
* @throws AlipayApiException
|
*/
|
public static void sendTemplateMsg(AlipayAppInfo app, String templateId, String page, String userId, String formId, String... params) throws AlipayApiException, AlipayXcxException {
|
AlipayClient alipayClient = AlipayUtil.getAlipayClient(app);
|
AlipayOpenAppMiniTemplatemessageSendRequest request = new AlipayOpenAppMiniTemplatemessageSendRequest();
|
JSONObject content = new JSONObject();
|
content.put("to_user_id", userId);
|
content.put("form_id", formId);
|
content.put("user_template_id", templateId);
|
content.put("page", page);
|
|
if (params != null && params.length > 0) {
|
JSONObject data = new JSONObject();
|
for (int i = 0; i < params.length; i++) {
|
JSONObject item = new JSONObject();
|
item.put("value", params[i]);
|
data.put("keyword" + (i + 1), item);
|
}
|
content.put("data", data.toJSONString());
|
}
|
|
System.out.println(content.toString());
|
request.setBizContent(content.toString());
|
AlipayOpenAppMiniTemplatemessageSendResponse response = app.getCertInfo() != null ? alipayClient.certificateExecute(request) : alipayClient.execute(request);
|
if (!response.isSuccess()) {
|
throw new AlipayXcxException(response.getCode(), response.getSubMsg(), response.getBody());
|
}
|
}
|
|
}
|